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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,15 @@ 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 API includes an in-memory fake payment lifecycle for bounty payouts:

- `POST /payments/send` creates a pending payment. Include `recipient`, `amount`, `currency`, and optional `repository`, `issue_number`, `bounty_id`, or `idempotency_key`.
- `GET /payments/list` returns payments, optionally filtered by `status`, `recipient`, or `repository`.
- `POST /payments/get` accepts `payment_id` and returns one payment.
- `POST /payments/complete` marks a pending payment as completed.
- `POST /payments/cancel` marks a pending payment as canceled.

Repeated `/payments/send` calls with the same `idempotency_key` body field or `Idempotency-Key` header return the original payment instead of creating duplicates.
110 changes: 104 additions & 6 deletions lib/db/db-client.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
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 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) => ({
const initializer = combine(databaseSchema.parse({}), (set, get) => ({
addThing: (thing: Omit<Thing, "thing_id">) => {
set((state) => ({
things: [
Expand All @@ -21,4 +26,97 @@ 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 createdPayment: Payment | undefined

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

if (existingPayment) {
createdPayment = existingPayment
return state
}

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

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

if (!createdPayment) {
throw new Error("Failed to create payment")
}

return createdPayment
},
findPayment: (paymentId: string) => {
return get().payments.find((payment) => payment.payment_id === paymentId)
},
listPayments: (filters: {
status?: PaymentStatus
recipient?: string
repository?: string
}) => {
return get().payments.filter((payment) => {
return (
(!filters.status || payment.status === filters.status) &&
(!filters.recipient || payment.recipient === filters.recipient) &&
(!filters.repository || payment.repository === filters.repository)
)
})
},
transitionPayment: (
paymentId: string,
status: Exclude<PaymentStatus, "pending">,
) => {
let updatedPayment: Payment | undefined
let transitionError: "not_found" | "terminal" | undefined

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

if (!payment) {
transitionError = "not_found"
return state
}

if (payment.status !== "pending") {
transitionError = "terminal"
updatedPayment = payment
return state
}

const now = new Date().toISOString()
const payments = state.payments.map((storedPayment) => {
if (storedPayment.payment_id !== paymentId) return storedPayment
updatedPayment = { ...storedPayment, status, updated_at: now }
return updatedPayment
})

return { payments }
})

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

export const paymentStatusSchema = z.enum(["pending", "completed", "canceled"])
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(),
repository: z.string().optional(),
issue_number: z.number().int().positive().optional(),
bounty_id: 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),
things: z.array(thingSchema).default([]),
paymentIdCounter: z.number().default(0),
payments: z.array(paymentSchema).default([]),
})
export type DatabaseSchema = z.infer<typeof databaseSchema>
4 changes: 3 additions & 1 deletion lib/middleware/with-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import type { DbClient } from "lib/db/db-client"
import { createDatabase } from "lib/db/db-client"
import type { Middleware } from "winterspec"

const defaultDb = createDatabase()
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 Scope default DB instance per app context

Move DB initialization out of module scope: creating defaultDb once at import time makes all routes that rely on withDb share state across the entire process, so separate Winterspec bundles or test runs in the same process can see each other’s payments/things and become order-dependent. This introduces cross-instance data bleed rather than just per-request persistence.

Useful? React with 👍 / 👎.


export const withDb: Middleware<
{},
{
db: DbClient
}
> = async (req, ctx, next) => {
if (!ctx.db) {
ctx.db = createDatabase()
ctx.db = defaultDb
}
return next(req, ctx)
}
34 changes: 34 additions & 0 deletions lib/payments/route-schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { paymentSchema, paymentStatusSchema } from "lib/db/schema"
import { z } from "zod"

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

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

export const listPaymentsQuerySchema = z.object({
status: paymentStatusSchema.optional(),
recipient: z.string().optional(),
repository: z.string().optional(),
})

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

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

export const paymentErrorResponseSchema = z.object({
error: z.string(),
})
27 changes: 27 additions & 0 deletions routes/payments/cancel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import {
paymentErrorResponseSchema,
paymentIdRequestSchema,
paymentResponseSchema,
} from "lib/payments/route-schemas"

export default withRouteSpec({
methods: ["POST"],
jsonBody: paymentIdRequestSchema,
jsonResponse: paymentResponseSchema.or(paymentErrorResponseSchema),
})(async (req, ctx) => {
const { payment_id } = await req.json()
const { payment, error } = ctx.db.transitionPayment(payment_id, "canceled")

if (error === "not_found") {
return ctx.json({ error: "Payment not found" }, { status: 404 })
}
if (error === "terminal") {
return ctx.json({ error: "Payment is already terminal" }, { status: 409 })
}
if (!payment) {
return ctx.json({ error: "Payment transition failed" }, { status: 500 })
}

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

export default withRouteSpec({
methods: ["POST"],
jsonBody: paymentIdRequestSchema,
jsonResponse: paymentResponseSchema.or(paymentErrorResponseSchema),
})(async (req, ctx) => {
const { payment_id } = await req.json()
const { payment, error } = ctx.db.transitionPayment(payment_id, "completed")

if (error === "not_found") {
return ctx.json({ error: "Payment not found" }, { status: 404 })
}
if (error === "terminal") {
return ctx.json({ error: "Payment is already terminal" }, { status: 409 })
}
if (!payment) {
return ctx.json({ error: "Payment transition failed" }, { status: 500 })
}

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

export default withRouteSpec({
methods: ["POST"],
jsonBody: paymentIdRequestSchema,
jsonResponse: paymentResponseSchema.or(paymentErrorResponseSchema),
})(async (req, ctx) => {
const { payment_id } = await req.json()
const payment = ctx.db.findPayment(payment_id)

if (!payment) return ctx.json({ error: "Payment not found" }, { status: 404 })

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

export default withRouteSpec({
methods: ["GET"],
queryParams: listPaymentsQuerySchema,
jsonResponse: listPaymentsResponseSchema,
})((req, ctx) => {
return ctx.json({ payments: ctx.db.listPayments(req.query) })
})
22 changes: 22 additions & 0 deletions routes/payments/send.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import {
paymentResponseSchema,
sendPaymentRequestSchema,
} from "lib/payments/route-schemas"

export default withRouteSpec({
methods: ["POST"],
jsonBody: sendPaymentRequestSchema,
jsonResponse: paymentResponseSchema,
})(async (req, ctx) => {
const paymentRequest = await req.json()
const payment = ctx.db.sendPayment({
...paymentRequest,
idempotency_key:
paymentRequest.idempotency_key ??
req.headers.get("Idempotency-Key") ??
undefined,
})

return ctx.json({ payment })
})
Loading