Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,43 @@ This is a template project with best-practice modules:
- Winterspec for defining the API
- bun testing
- Zustand store with zod definition for database state

## Fake payment API

The payment routes provide a small in-memory API for simulating bounty payouts.

### Send a payment

`POST /payments/send`

```json
{
"recipient": "octocat",
"amount": 10,
"currency": "USD",
"bounty_id": "fake-algora-1",
"issue_number": 1,
"repository": "tscircuit/fake-algora",
"idempotency_key": "optional-retry-key"
}
```

### Read payments

- `GET /payments/list`
- `GET /payments/list?recipient=octocat&status=pending`
- `GET /payments/get?payment_id=0`

### Transition payments

- `POST /payments/complete`
- `POST /payments/cancel`
- `POST /payments/fail`

Each transition accepts:

```json
{
"payment_id": "0"
}
```
130 changes: 124 additions & 6 deletions lib/db/db-client.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,32 @@
import { createStore, type StoreApi } from "zustand/vanilla"
import { immer } from "zustand/middleware/immer"
import { hoist, type HoistedStoreApi } from "zustand-hoist"

import { databaseSchema, type DatabaseSchema, type Thing } from "./schema.ts"
import { hoist } from "zustand-hoist"
import { combine } from "zustand/middleware"
import { createStore } from "zustand/vanilla"

import {
type Payment,
type PaymentStatus,
type Thing,
databaseSchema,
} from "./schema.ts"

export const createDatabase = () => {
return hoist(createStore(initializer))
}

export type DbClient = ReturnType<typeof createDatabase>

const initializer = combine(databaseSchema.parse({}), (set) => ({
export interface CreatePaymentInput {
recipient: string
amount: number
currency?: string
bounty_id?: string
issue_number?: number
repository?: string
idempotency_key?: string
note?: string
}

const initializer = combine(databaseSchema.parse({}), (set, get) => ({
addThing: (thing: Omit<Thing, "thing_id">) => {
set((state) => ({
things: [
Expand All @@ -21,4 +36,107 @@ const initializer = combine(databaseSchema.parse({}), (set) => ({
idCounter: state.idCounter + 1,
}))
},
createPayment: (input: CreatePaymentInput) => {
let result: { payment: Payment; idempotent_replay: boolean } | undefined

set((state) => {
const existingPayment = input.idempotency_key
? state.payments.find(
(payment) => payment.idempotency_key === input.idempotency_key,
)
: undefined

if (existingPayment) {
result = {
payment: existingPayment,
idempotent_replay: true,
}
return {}
}

const now = new Date().toISOString()
const payment: Payment = {
payment_id: state.paymentIdCounter.toString(),
recipient: input.recipient,
amount: input.amount,
currency: input.currency ?? "USD",
status: "pending",
bounty_id: input.bounty_id,
issue_number: input.issue_number,
repository: input.repository,
idempotency_key: input.idempotency_key,
note: input.note,
created_at: now,
updated_at: now,
}

result = {
payment,
idempotent_replay: false,
}

return {
payments: [...state.payments, payment],
paymentIdCounter: state.paymentIdCounter + 1,
}
})

if (!result) {
throw new Error("Payment was not created")
}

return result
},
listPayments: (filters: {
recipient?: string
status?: PaymentStatus
repository?: string
}) => {
return get().payments.filter((payment) => {
if (filters.recipient && payment.recipient !== filters.recipient) {
return false
}
if (filters.status && payment.status !== filters.status) {
return false
}
if (filters.repository && payment.repository !== filters.repository) {
return false
}
return true
})
},
getPayment: (payment_id: string) => {
return get().payments.find((payment) => payment.payment_id === payment_id)
},
updatePaymentStatus: (payment_id: string, status: PaymentStatus) => {
let updatedPayment: Payment | undefined

set((state) => {
const now = new Date().toISOString()
const payments = state.payments.map((payment) => {
if (payment.payment_id !== payment_id) {
return payment
}

updatedPayment = {
...payment,
status,
updated_at: now,
completed_at:
status === "completed" ? payment.completed_at ?? now : undefined,
canceled_at:
status === "canceled" ? payment.canceled_at ?? now : undefined,
failed_at: status === "failed" ? payment.failed_at ?? now : undefined,
}

return updatedPayment
})

return {
payments,
}
})

return updatedPayment
},
}))
29 changes: 29 additions & 0 deletions lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,37 @@ export const thingSchema = z.object({
})
export type Thing = z.infer<typeof thingSchema>

export const paymentStatusSchema = z.enum([
"pending",
"completed",
"canceled",
"failed",
])
export type PaymentStatus = z.infer<typeof paymentStatusSchema>

export const paymentSchema = z.object({
payment_id: z.string(),
recipient: z.string(),
amount: z.number(),
currency: z.string(),
status: paymentStatusSchema,
bounty_id: z.string().optional(),
issue_number: z.number().optional(),
repository: z.string().optional(),
idempotency_key: z.string().optional(),
note: z.string().optional(),
created_at: z.string(),
updated_at: z.string(),
completed_at: z.string().optional(),
canceled_at: z.string().optional(),
failed_at: z.string().optional(),
})
export type Payment = z.infer<typeof paymentSchema>

export const databaseSchema = z.object({
idCounter: z.number().default(0),
things: z.array(thingSchema).default([]),
paymentIdCounter: z.number().default(0),
payments: z.array(paymentSchema).default([]),
})
export type DatabaseSchema = z.infer<typeof databaseSchema>
33 changes: 33 additions & 0 deletions lib/payments/schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { paymentSchema } from "lib/db/schema"
import { z } from "zod"

export const sendPaymentBodySchema = z.object({
recipient: z.string().min(1),
amount: z.number().positive(),
currency: z.string().min(1).default("USD"),
bounty_id: z.string().min(1).optional(),
issue_number: z.number().int().positive().optional(),
repository: z.string().min(1).optional(),
idempotency_key: z.string().min(1).optional(),
note: z.string().optional(),
})

export const paymentResponseSchema = z.object({
payment: paymentSchema,
})

export const sendPaymentResponseSchema = paymentResponseSchema.extend({
idempotent_replay: z.boolean(),
})

export const nullablePaymentResponseSchema = z.object({
payment: paymentSchema.nullable(),
})

export const listPaymentsResponseSchema = z.object({
payments: z.array(paymentSchema),
})

export const transitionPaymentBodySchema = z.object({
payment_id: z.string().min(1),
})
16 changes: 16 additions & 0 deletions routes/payments/cancel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import {
nullablePaymentResponseSchema,
transitionPaymentBodySchema,
} from "lib/payments/schemas"

export default withRouteSpec({
methods: ["POST"],
jsonBody: transitionPaymentBodySchema,
jsonResponse: nullablePaymentResponseSchema,
})(async (req, ctx) => {
const { payment_id } = transitionPaymentBodySchema.parse(await req.json())
const payment = ctx.db.updatePaymentStatus(payment_id, "canceled")

return ctx.json({ payment: payment ?? null })
})
16 changes: 16 additions & 0 deletions routes/payments/complete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import {
nullablePaymentResponseSchema,
transitionPaymentBodySchema,
} from "lib/payments/schemas"

export default withRouteSpec({
methods: ["POST"],
jsonBody: transitionPaymentBodySchema,
jsonResponse: nullablePaymentResponseSchema,
})(async (req, ctx) => {
const { payment_id } = transitionPaymentBodySchema.parse(await req.json())
const payment = ctx.db.updatePaymentStatus(payment_id, "completed")

return ctx.json({ payment: payment ?? null })
})
16 changes: 16 additions & 0 deletions routes/payments/fail.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import {
nullablePaymentResponseSchema,
transitionPaymentBodySchema,
} from "lib/payments/schemas"

export default withRouteSpec({
methods: ["POST"],
jsonBody: transitionPaymentBodySchema,
jsonResponse: nullablePaymentResponseSchema,
})(async (req, ctx) => {
const { payment_id } = transitionPaymentBodySchema.parse(await req.json())
const payment = ctx.db.updatePaymentStatus(payment_id, "failed")

return ctx.json({ payment: payment ?? null })
})
12 changes: 12 additions & 0 deletions routes/payments/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { nullablePaymentResponseSchema } from "lib/payments/schemas"

export default withRouteSpec({
methods: ["GET"],
jsonResponse: nullablePaymentResponseSchema,
})((req, ctx) => {
const paymentId = new URL(req.url).searchParams.get("payment_id")
const payment = paymentId ? ctx.db.getPayment(paymentId) : undefined

return ctx.json({ payment: payment ?? null })
})
19 changes: 19 additions & 0 deletions routes/payments/list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { paymentStatusSchema } from "lib/db/schema"
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { listPaymentsResponseSchema } from "lib/payments/schemas"

export default withRouteSpec({
methods: ["GET"],
jsonResponse: listPaymentsResponseSchema,
})((req, ctx) => {
const searchParams = new URL(req.url).searchParams
const status = paymentStatusSchema.safeParse(searchParams.get("status"))

const payments = ctx.db.listPayments({
recipient: searchParams.get("recipient") ?? undefined,
repository: searchParams.get("repository") ?? undefined,
status: status.success ? status.data : undefined,
})

return ctx.json({ payments })
})
16 changes: 16 additions & 0 deletions routes/payments/send.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import {
sendPaymentBodySchema,
sendPaymentResponseSchema,
} from "lib/payments/schemas"

export default withRouteSpec({
methods: ["POST"],
jsonBody: sendPaymentBodySchema,
jsonResponse: sendPaymentResponseSchema,
})(async (req, ctx) => {
const body = sendPaymentBodySchema.parse(await req.json())
const result = ctx.db.createPayment(body)

return ctx.json(result)
})
Loading