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
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,17 @@ 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 payments API stores fake payment records in memory and supports a small
payment lifecycle:

- `POST /payments/send` creates a pending payment. Reusing an
`idempotency_key` returns the existing payment instead of creating a
duplicate.
- `GET /payments/list` returns payments and can filter by `recipient`,
`repository`, or `status`.
- `GET /payments/get?payment_id=0` returns a payment by id.
- `POST /payments/update-status` moves a pending payment to `completed`,
`canceled`, or `failed`. Terminal payments cannot be changed again.
83 changes: 80 additions & 3 deletions lib/db/db-client.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
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))
Expand All @@ -21,4 +27,75 @@ const initializer = combine(databaseSchema.parse({}), (set) => ({
idCounter: state.idCounter + 1,
}))
},
sendPayment: (
payment: Omit<
Payment,
"payment_id" | "status" | "created_at" | "updated_at"
>,
) => {
const now = new Date().toISOString()
let nextPayment: Payment | undefined

set((state) => {
if (payment.idempotency_key) {
const existing = state.payments.find(
(storedPayment) =>
storedPayment.idempotency_key === payment.idempotency_key,
)

if (existing) {
nextPayment = existing
return {}
}
}

nextPayment = {
...payment,
payment_id: state.paymentIdCounter.toString(),
status: "pending",
created_at: now,
updated_at: now,
}

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

return nextPayment!
},
updatePaymentStatus: (
paymentId: string,
status: Exclude<PaymentStatus, "pending">,
) => {
const now = new Date().toISOString()
let updatedPayment: Payment | undefined

set((state) => {
const payment = state.payments.find(
(storedPayment) => storedPayment.payment_id === paymentId,
)

if (!payment || payment.status !== "pending") {
return {}
}

updatedPayment = {
...payment,
status,
updated_at: now,
}

return {
payments: state.payments.map((storedPayment) =>
storedPayment.payment_id === paymentId
? updatedPayment!
: storedPayment,
),
}
})

return updatedPayment
},
}))
24 changes: 24 additions & 0 deletions lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,32 @@ 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(),
bounty_issue: z.number().optional(),
repository: z.string().optional(),
idempotency_key: z.string().optional(),
status: paymentStatusSchema,
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),
paymentIdCounter: z.number().default(0),
things: z.array(thingSchema).default([]),
payments: z.array(paymentSchema).default([]),
})
export type DatabaseSchema = z.infer<typeof databaseSchema>
21 changes: 21 additions & 0 deletions routes/payments/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { paymentSchema } from "lib/db/schema"
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

export default withRouteSpec({
methods: ["GET"],
queryParams: z.object({
payment_id: z.string().min(1),
}),
jsonResponse: z.object({
payment: paymentSchema.optional(),
}),
})((req, ctx) => {
const url = new URL(req.url)
const paymentId = url.searchParams.get("payment_id")
const payment = ctx.db.payments.find(
(storedPayment) => storedPayment.payment_id === paymentId,
)

return ctx.json({ payment })
})
29 changes: 29 additions & 0 deletions routes/payments/list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
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 recipient = url.searchParams.get("recipient")
const repository = url.searchParams.get("repository")
const statusParam = url.searchParams.get("status")
const status = statusParam
? paymentStatusSchema.safeParse(statusParam)
: undefined

const payments = ctx.db.payments.filter((payment) => {
if (recipient && payment.recipient !== recipient) return false
if (repository && payment.repository !== repository) return false
if (status && (!status.success || payment.status !== status.data)) {
return false
}
return true
})

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

const sendPaymentRequestSchema = z.object({
recipient: z.string().min(1),
amount: z.number().positive(),
currency: z.string().min(1).default("USD"),
bounty_issue: z.number().int().positive().optional(),
repository: z.string().min(1).optional(),
idempotency_key: z.string().min(1).optional(),
})

export default withRouteSpec({
methods: ["POST"],
jsonBody: sendPaymentRequestSchema,
jsonResponse: z.object({
payment: paymentSchema,
}),
})(async (req, ctx) => {
const body = sendPaymentRequestSchema.parse(await req.json())
const payment = ctx.db.sendPayment(body)

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

const updateStatusRequestSchema = z.object({
payment_id: z.string().min(1),
status: z.enum(["completed", "canceled", "failed"]),
})

export default withRouteSpec({
methods: ["POST"],
jsonBody: updateStatusRequestSchema,
jsonResponse: z.object({
payment: paymentSchema.optional(),
}),
})(async (req, ctx) => {
const { payment_id, status } = updateStatusRequestSchema.parse(
await req.json(),
)
const payment = ctx.db.updatePaymentStatus(payment_id, status)

return ctx.json({ payment })
})
78 changes: 78 additions & 0 deletions tests/routes/payments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
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: "surim0n",
amount: 10,
currency: "USD",
bounty_issue: 1,
repository: "tscircuit/fake-algora",
idempotency_key: "issue-1-payment",
})

expect(sendResponse.data.payment).toMatchObject({
payment_id: "0",
recipient: "surim0n",
amount: 10,
currency: "USD",
bounty_issue: 1,
repository: "tscircuit/fake-algora",
idempotency_key: "issue-1-payment",
status: "pending",
})

const duplicateResponse = await axios.post("/payments/send", {
recipient: "surim0n",
amount: 10,
currency: "USD",
idempotency_key: "issue-1-payment",
})

expect(duplicateResponse.data.payment.payment_id).toBe("0")

const listResponse = await axios.get(
"/payments/list?recipient=surim0n&status=pending",
)

expect(listResponse.data.payments).toHaveLength(1)

const getResponse = await axios.get("/payments/get?payment_id=0")

expect(getResponse.data.payment.recipient).toBe("surim0n")

const completeResponse = await axios.post("/payments/update-status", {
payment_id: "0",
status: "completed",
})

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

test("completed payments cannot be moved into another terminal status", async () => {
const { axios } = await getTestServer()

await axios.post("/payments/send", {
recipient: "maintainer",
amount: 25,
})

await axios.post("/payments/update-status", {
payment_id: "0",
status: "completed",
})

const cancelResponse = await axios.post("/payments/update-status", {
payment_id: "0",
status: "canceled",
})

expect(cancelResponse.data.payment).toBeUndefined()

const listResponse = await axios.get("/payments/list?status=completed")

expect(listResponse.data.payments).toHaveLength(1)
expect(listResponse.data.payments[0].status).toBe("completed")
})