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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,11 @@ This is a template project with best-practice modules:
- Winterspec for defining the API
- bun testing
- Zustand store with zod definition for database state

## Payment Routes

- `POST /payments/send` - create a fake payment record
- `GET /payments/list` - list fake payment records
- `POST /payments/get` - fetch a payment by id
- `POST /payments/complete` - mark a payment as completed
- `POST /payments/cancel` - mark a payment as canceled
50 changes: 48 additions & 2 deletions lib/db/db-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ 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 {
databaseSchema,
type DatabaseSchema,
type Payment,
type PaymentStatus,
type Thing,
} from "./schema.ts"
import { combine } from "zustand/middleware"

export const createDatabase = () => {
Expand All @@ -11,7 +17,7 @@ export const createDatabase = () => {

export type DbClient = ReturnType<typeof createDatabase>

const initializer = combine(databaseSchema.parse({}), (set) => ({
const initializer = combine(databaseSchema.parse({}), (set, get) => ({
addThing: (thing: Omit<Thing, "thing_id">) => {
set((state) => ({
things: [
Expand All @@ -21,4 +27,44 @@ const initializer = combine(databaseSchema.parse({}), (set) => ({
idCounter: state.idCounter + 1,
}))
},
addPayment: (
payment: Omit<
Payment,
"payment_id" | "status" | "created_at" | "updated_at" | "metadata"
> & {
metadata?: Record<string, string>
},
) => {
const now = new Date().toISOString()
set((state) => ({
payments: [
...state.payments,
{
...payment,
payment_id: state.idCounter.toString(),
status: "pending",
metadata: payment.metadata ?? {},
created_at: now,
updated_at: now,
},
],
idCounter: state.idCounter + 1,
}))
},
findPaymentById: (payment_id: string) => {
return get().payments.find((p) => p.payment_id === payment_id)
},
findPaymentByIdempotencyKey: (idempotency_key: string) => {
return get().payments.find((p) => p.idempotency_key === idempotency_key)
},
updatePaymentStatus: (payment_id: string, status: PaymentStatus) => {
const now = new Date().toISOString()
set((state) => ({
payments: state.payments.map((payment) =>
payment.payment_id === payment_id
? { ...payment, status, updated_at: now }
: payment,
),
}))
},
}))
23 changes: 23 additions & 0 deletions lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,31 @@ 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().positive(),
currency: z.string().default("USD"),
status: paymentStatusSchema.default("pending"),
idempotency_key: z.string().optional(),
bounty_issue: z.string().optional(),
metadata: z.record(z.string(), z.string()).default({}),
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),
things: z.array(thingSchema).default([]),
payments: z.array(paymentSchema).default([]),
})
export type DatabaseSchema = z.infer<typeof databaseSchema>
46 changes: 46 additions & 0 deletions routes/payments/cancel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

const updatePaymentSchema = z.object({
payment_id: z.string().min(1),
})

export default withRouteSpec({
methods: ["POST"],
jsonBody: updatePaymentSchema,
jsonResponse: z.object({
ok: z.boolean(),
payment: z
.object({
payment_id: z.string(),
recipient: z.string(),
amount: z.number(),
currency: z.string(),
status: z.enum(["pending", "completed", "canceled", "failed"]),
idempotency_key: z.string().optional(),
bounty_issue: z.string().optional(),
metadata: z.record(z.string(), z.string()),
created_at: z.string(),
updated_at: z.string(),
})
.nullable(),
error: z.string().optional(),
}),
})(async (req, ctx) => {
const { payment_id } = updatePaymentSchema.parse(await req.json())
const payment = ctx.db.findPaymentById(payment_id)
if (!payment) {
return ctx.json({
ok: false,
payment: null,
error: "payment_not_found",
})
}

ctx.db.updatePaymentStatus(payment_id, "canceled")

return ctx.json({
ok: true,
payment: ctx.db.findPaymentById(payment_id)!,
})
})
46 changes: 46 additions & 0 deletions routes/payments/complete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

const updatePaymentSchema = z.object({
payment_id: z.string().min(1),
})

export default withRouteSpec({
methods: ["POST"],
jsonBody: updatePaymentSchema,
jsonResponse: z.object({
ok: z.boolean(),
payment: z
.object({
payment_id: z.string(),
recipient: z.string(),
amount: z.number(),
currency: z.string(),
status: z.enum(["pending", "completed", "canceled", "failed"]),
idempotency_key: z.string().optional(),
bounty_issue: z.string().optional(),
metadata: z.record(z.string(), z.string()),
created_at: z.string(),
updated_at: z.string(),
})
.nullable(),
error: z.string().optional(),
}),
})(async (req, ctx) => {
const { payment_id } = updatePaymentSchema.parse(await req.json())
const payment = ctx.db.findPaymentById(payment_id)
if (!payment) {
return ctx.json({
ok: false,
payment: null,
error: "payment_not_found",
})
}

ctx.db.updatePaymentStatus(payment_id, "completed")

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

const getPaymentBodySchema = z.object({
payment_id: z.string().min(1),
})

export default withRouteSpec({
methods: ["POST"],
jsonBody: getPaymentBodySchema,
jsonResponse: z.object({
ok: z.boolean(),
payment: z
.object({
payment_id: z.string(),
recipient: z.string(),
amount: z.number(),
currency: z.string(),
status: z.enum(["pending", "completed", "canceled", "failed"]),
idempotency_key: z.string().optional(),
bounty_issue: z.string().optional(),
metadata: z.record(z.string(), z.string()),
created_at: z.string(),
updated_at: z.string(),
})
.nullable(),
error: z.string().optional(),
}),
})(async (req, ctx) => {
const { payment_id } = getPaymentBodySchema.parse(await req.json())
const payment = ctx.db.findPaymentById(payment_id)

if (!payment) {
return ctx.json({
ok: false,
payment: null,
error: "payment_not_found",
})
}

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

export default withRouteSpec({
methods: ["GET"],
jsonResponse: z.object({
payments: z.array(
z.object({
payment_id: z.string(),
recipient: z.string(),
amount: z.number(),
currency: z.string(),
status: z.enum(["pending", "completed", "canceled", "failed"]),
idempotency_key: z.string().optional(),
bounty_issue: z.string().optional(),
metadata: z.record(z.string(), z.string()),
created_at: z.string(),
updated_at: z.string(),
}),
),
}),
})(async (_req, ctx) => {
return ctx.json({
payments: ctx.db.getState().payments,
})
})
55 changes: 55 additions & 0 deletions routes/payments/send.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

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

export default withRouteSpec({
methods: ["POST"],
jsonBody: sendPaymentBodySchema,
jsonResponse: z.object({
ok: z.boolean(),
payment: z.object({
payment_id: z.string(),
recipient: z.string(),
amount: z.number(),
currency: z.string(),
status: z.enum(["pending", "completed", "canceled", "failed"]),
idempotency_key: z.string().optional(),
bounty_issue: z.string().optional(),
metadata: z.record(z.string(), z.string()),
created_at: z.string(),
updated_at: z.string(),
}),
idempotent_replay: z.boolean().optional(),
}),
})(async (req, ctx) => {
const body = sendPaymentBodySchema.parse(await req.json())

if (body.idempotency_key) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle empty idempotency keys consistently

The replay guard uses a truthiness check (if (body.idempotency_key)), but the request schema allows idempotency_key: "" because it is z.string().optional(). In that case, the deduplication branch is skipped and repeated POST /payments/send calls with the same empty key create duplicate payments, which breaks the endpoint’s advertised idempotent retry behavior for this input.

Useful? React with 👍 / 👎.

const existing = ctx.db.findPaymentByIdempotencyKey(body.idempotency_key)
if (existing) {
return ctx.json({
ok: true,
payment: existing,
idempotent_replay: true,
})
}
}

ctx.db.addPayment(body)
const payment = body.idempotency_key
? ctx.db.findPaymentByIdempotencyKey(body.idempotency_key)
: ctx.db.getState().payments.at(-1)

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

test("payment lifecycle routes work and support idempotent send", async () => {
const { axios } = await getTestServer()

const sendBody = {
recipient: "dev@example.com",
amount: 30,
currency: "USD",
idempotency_key: "issue-1-send-001",
bounty_issue: "#1",
metadata: {
source: "algora",
},
}

const firstSend = await axios.post("/payments/send", sendBody)
expect(firstSend.data.ok).toBe(true)
expect(firstSend.data.payment.status).toBe("pending")

const replaySend = await axios.post("/payments/send", sendBody)
expect(replaySend.data.ok).toBe(true)
expect(replaySend.data.idempotent_replay).toBe(true)
expect(replaySend.data.payment.payment_id).toBe(
firstSend.data.payment.payment_id,
)

const paymentId = firstSend.data.payment.payment_id

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

const getRes = await axios.post("/payments/get", { payment_id: paymentId })
expect(getRes.data.ok).toBe(true)
expect(getRes.data.payment.payment_id).toBe(paymentId)

const completeRes = await axios.post("/payments/complete", {
payment_id: paymentId,
})
expect(completeRes.data.ok).toBe(true)
expect(completeRes.data.payment.status).toBe("completed")

const cancelRes = await axios.post("/payments/cancel", {
payment_id: paymentId,
})
expect(cancelRes.data.ok).toBe(true)
expect(cancelRes.data.payment.status).toBe("canceled")
})