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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,20 @@ 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 Payments API

The fake payment routes model the lifecycle needed by bounty-style flows without
contacting a real payment provider.

- `POST /payments/send`: create a pending fake payment. Accepts `recipient`,
`amount`, optional `currency`, bounty metadata, and optional
`idempotency_key`.
- `GET /payments/list`: list payments, optionally filtered by `recipient`,
`repository`, or `status`.
- `GET /payments/get?payment_id=pay_0`: fetch one payment by id.
- `POST /payments/complete`: mark a pending payment as completed.

When `idempotency_key` is supplied to `/payments/send`, repeated requests return
the original payment with `idempotent_replay: true` instead of creating duplicate
fake transfers.
105 changes: 101 additions & 4 deletions lib/db/db-client.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,36 @@
import { createStore, type StoreApi } from "zustand/vanilla"
import { type HoistedStoreApi, hoist } from "zustand-hoist"
import { immer } from "zustand/middleware/immer"
import { hoist, type HoistedStoreApi } from "zustand-hoist"
import { type StoreApi, createStore } from "zustand/vanilla"

import { databaseSchema, type DatabaseSchema, type Thing } from "./schema.ts"
import { combine } from "zustand/middleware"
import {
type DatabaseSchema,
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) => ({
type CreatePaymentInput = Omit<
Payment,
"payment_id" | "status" | "created_at" | "updated_at"
> & {
status?: PaymentStatus
}

const terminalStatuses = new Set<PaymentStatus>([
"completed",
"canceled",
"failed",
])

const initializer = combine(databaseSchema.parse({}), (set, get) => ({
addThing: (thing: Omit<Thing, "thing_id">) => {
set((state) => ({
things: [
Expand All @@ -21,4 +40,82 @@ const initializer = combine(databaseSchema.parse({}), (set) => ({
idCounter: state.idCounter + 1,
}))
},
createPayment: (input: CreatePaymentInput) => {
const existingPayment = input.idempotency_key
? get().payments.find(
(payment) => payment.idempotency_key === input.idempotency_key,
)
: undefined

if (existingPayment) {
return { payment: existingPayment, idempotentReplay: true }
}

const timestamp = new Date().toISOString()
const payment: Payment = {
...input,
payment_id: `pay_${get().paymentCounter}`,
currency: input.currency || "USD",
status: input.status || "pending",
created_at: timestamp,
updated_at: timestamp,
}

set((state) => ({
payments: [...state.payments, payment],
paymentCounter: state.paymentCounter + 1,
}))

return { payment, idempotentReplay: false }
},
findPaymentById: (paymentId: string) => {
return (
get().payments.find((payment) => payment.payment_id === paymentId) ?? null
)
},
listPayments: (filters?: {
recipient?: string
repository?: string
status?: PaymentStatus
}) => {
return get().payments.filter((payment) => {
if (filters?.recipient && payment.recipient !== filters.recipient) {
return false
}
if (filters?.repository && payment.repository !== filters.repository) {
return false
}
if (filters?.status && payment.status !== filters.status) {
return false
}
return true
})
},
updatePaymentStatus: (paymentId: string, status: PaymentStatus) => {
const existingPayment = get().payments.find(
(payment) => payment.payment_id === paymentId,
)

if (!existingPayment) {
return null
}

if (terminalStatuses.has(existingPayment.status)) {
return existingPayment
}

const updatedPayment: Payment = {
...existingPayment,
status,
updated_at: new Date().toISOString(),
}

set((state) => ({
payments: state.payments.map((payment) =>
payment.payment_id === paymentId ? updatedPayment : payment,
),
}))

return updatedPayment
},
}))
25 changes: 25 additions & 0 deletions lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,33 @@ 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(),
created_at: z.string(),
updated_at: z.string(),
})
export type Payment = z.infer<typeof paymentSchema>

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

export default withRouteSpec({
methods: ["POST"],
jsonBody: z.object({
payment_id: z.string().min(1),
}),
jsonResponse: z.object({
ok: z.boolean(),
payment: paymentSchema.nullable(),
}),
})(async (req, ctx) => {
const { payment_id } = await req.json()
const payment = ctx.db.updatePaymentStatus(payment_id, "completed")

return ctx.json({
ok: Boolean(payment),
payment,
})
})
17 changes: 17 additions & 0 deletions routes/payments/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { paymentSchema } from "lib/db/schema"
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

export default withRouteSpec({
methods: ["GET"],
jsonResponse: z.object({
payment: paymentSchema.nullable(),
}),
})((req, ctx) => {
const url = new URL(req.url)
const paymentId = url.searchParams.get("payment_id")

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

export default withRouteSpec({
methods: ["GET"],
jsonResponse: z.object({
payments: z.array(paymentSchema),
}),
})((req, ctx) => {
const url = new URL(req.url)
const status = paymentStatusSchema
.optional()
.parse(url.searchParams.get("status") ?? undefined)

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

return ctx.json({ payments })
})
31 changes: 31 additions & 0 deletions routes/payments/send.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { paymentSchema } from "lib/db/schema"
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

export default withRouteSpec({
methods: ["POST"],
jsonBody: z.object({
recipient: z.string().min(1),
amount: z.number().positive(),
currency: z.string().min(1).optional(),
bounty_id: z.string().optional(),
issue_number: z.number().optional(),
repository: z.string().optional(),
idempotency_key: z.string().optional(),
}),
jsonResponse: z.object({
payment: paymentSchema,
idempotent_replay: z.boolean(),
}),
})(async (req, ctx) => {
const body = await req.json()
const { payment, idempotentReplay } = ctx.db.createPayment({
...body,
currency: body.currency || "USD",
})

return ctx.json({
payment,
idempotent_replay: idempotentReplay,
})
})
68 changes: 68 additions & 0 deletions tests/routes/payments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { expect, test } from "bun:test"
import { getTestServer } from "tests/fixtures/get-test-server"

test("send, list, get, and complete a payment", async () => {
const { axios } = await getTestServer()

const sendResponse = await axios.post("/payments/send", {
recipient: "[email protected]",
amount: 10,
bounty_id: "bounty_1",
issue_number: 1,
repository: "tscircuit/fake-algora",
})

expect(sendResponse.data.idempotent_replay).toBe(false)
expect(sendResponse.data.payment).toMatchObject({
payment_id: "pay_0",
recipient: "[email protected]",
amount: 10,
currency: "USD",
status: "pending",
bounty_id: "bounty_1",
issue_number: 1,
repository: "tscircuit/fake-algora",
})

const listResponse = await axios.get(
"/payments/list?recipient=dev%40example.com&status=pending",
)

expect(listResponse.data.payments).toHaveLength(1)
expect(listResponse.data.payments[0].payment_id).toBe("pay_0")

const getResponse = await axios.get("/payments/get?payment_id=pay_0")
expect(getResponse.data.payment.payment_id).toBe("pay_0")

const completeResponse = await axios.post("/payments/complete", {
payment_id: "pay_0",
})

expect(completeResponse.data.ok).toBe(true)
expect(completeResponse.data.payment.status).toBe("completed")
})

test("send replays existing payment for matching idempotency key", async () => {
const { axios } = await getTestServer()

const firstResponse = await axios.post("/payments/send", {
recipient: "[email protected]",
amount: 5,
idempotency_key: "retry-safe-key",
})

const secondResponse = await axios.post("/payments/send", {
recipient: "[email protected]",
amount: 5,
idempotency_key: "retry-safe-key",
})

expect(firstResponse.data.idempotent_replay).toBe(false)
expect(secondResponse.data.idempotent_replay).toBe(true)
expect(secondResponse.data.payment.payment_id).toBe(
firstResponse.data.payment.payment_id,
)

const listResponse = await axios.get("/payments/list")
expect(listResponse.data.payments).toHaveLength(1)
})