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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,23 @@ 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 endpoints support a simple bounty payout lifecycle:

- `POST /payments/send` creates a pending payment. Optional `idempotency_key`
values make retries safe for the same recipient.
- `GET /payments/list` lists payments and supports `recipient`, `status`, and
`repository` query filters.
- `GET /payments/get?payment_id=<id>` returns one payment.
- `POST /payments/complete`, `POST /payments/cancel`, and `POST /payments/fail`
transition pending payments into terminal states.

Example:

```bash
curl -X POST http://localhost:3000/payments/send \
-H 'content-type: application/json' \
-d '{"recipient":"agent@example.com","amount":10,"currency":"USD","idempotency_key":"issue-1-agent"}'
```
106 changes: 101 additions & 5 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 { hoist } from "zustand-hoist"
import { createStore } from "zustand/vanilla"

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

const terminalPaymentStatuses = 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 +36,85 @@ const initializer = combine(databaseSchema.parse({}), (set) => ({
idCounter: state.idCounter + 1,
}))
},
createPayment: (payment: CreatePaymentInput) => {
let existingPayment: Payment | undefined
let createdPayment: Payment | undefined

set((state) => {
existingPayment = payment.idempotency_key
? state.payments.find(
(existing) =>
existing.idempotency_key === payment.idempotency_key &&
existing.recipient === payment.recipient,
)
: undefined

if (existingPayment) {
return state
}

const timestamp = new Date().toISOString()
createdPayment = {
...payment,
payment_id: state.paymentCounter.toString(),
status: "pending",
created_at: timestamp,
updated_at: timestamp,
}

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

return {
idempotent: Boolean(existingPayment),
payment: existingPayment ?? createdPayment!,
}
},
getPayment: (paymentId: string) => {
return get().payments.find((payment) => payment.payment_id === paymentId)
},
updatePaymentStatus: (paymentId: string, status: PaymentStatus) => {
let payment: Payment | undefined
let error: string | undefined

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

if (!existingPayment) {
error = "payment_not_found"
return state
}

if (terminalPaymentStatuses.has(existingPayment.status)) {
error = "payment_already_terminal"
payment = existingPayment
return state
}

const timestamp = new Date().toISOString()
payment = {
...existingPayment,
status,
updated_at: timestamp,
completed_at:
status === "completed" ? timestamp : existingPayment.completed_at,
canceled_at:
status === "canceled" ? timestamp : existingPayment.canceled_at,
failed_at: status === "failed" ? timestamp : existingPayment.failed_at,
}

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

return { error, payment }
},
}))
28 changes: 28 additions & 0 deletions lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,36 @@ 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(),
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([]),
paymentCounter: 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 db = createDatabase()

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

export const paymentResponseSchema = paymentSchema

export const paymentErrorResponseSchema = z.object({
error: z.string(),
})

export const paymentOrErrorResponseSchema = z.union([
z.object({
payment: paymentResponseSchema,
}),
paymentErrorResponseSchema,
])

export const paymentListResponseSchema = z.object({
payments: z.array(paymentResponseSchema),
})

export const paymentSendBodySchema = 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(),
})

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

export const sendPaymentResponseSchema = z.object({
idempotent: z.boolean(),
payment: paymentResponseSchema,
})
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"start": "bun run dev",
"dev": "winterspec dev",
"build": "winterspec bundle -o dist/bundle.js",
"next:dev": "next dev"
"next:dev": "next dev",
"test": "bun test"
}
}
23 changes: 23 additions & 0 deletions routes/payments/cancel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import {
paymentIdBodySchema,
paymentOrErrorResponseSchema,
} from "lib/payments/schemas"

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

if (error) {
return Response.json(
{ error },
{ status: error === "payment_not_found" ? 404 : 409 },
)
}

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

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

if (error) {
return Response.json(
{ error },
{ status: error === "payment_not_found" ? 404 : 409 },
)
}

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

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

if (error) {
return Response.json(
{ error },
{ status: error === "payment_not_found" ? 404 : 409 },
)
}

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

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

if (!paymentId) {
return Response.json({ error: "payment_id_required" }, { status: 400 })
}

const payment = ctx.db.getPayment(paymentId)

if (!payment) {
return Response.json({ error: "payment_not_found" }, { status: 404 })
}

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

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

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

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

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

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