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
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,28 @@ 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 project includes a small in-memory fake payment lifecycle API:

- `POST /payments/send` creates a pending payment and supports
`idempotency_key` for retry-safe sends.
- `GET /payments/list` lists payments and can filter by `recipient`,
`repository`, and `status`.
- `GET /payments/get?payment_id=pay_0` fetches one payment.
- `POST /payments/complete` marks a pending payment as completed.
- `POST /payments/cancel` marks a pending payment as canceled.

Example send body:

```json
{
"recipient": "maintainer@example.com",
"amount": 10,
"currency": "USD",
"repository": "tscircuit/fake-algora",
"issue_number": 1,
"idempotency_key": "retry-safe-payment"
}
```
106 changes: 101 additions & 5 deletions lib/db/db-client.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,35 @@
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 NewPayment = Pick<Payment, "recipient" | "amount"> &
Partial<
Pick<
Payment,
| "currency"
| "bounty_id"
| "issue_number"
| "repository"
| "idempotency_key"
>
>

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

const initializer = combine(databaseSchema.parse({}), (set, get) => ({
addThing: (thing: Omit<Thing, "thing_id">) => {
set((state) => ({
things: [
Expand All @@ -21,4 +39,82 @@ const initializer = combine(databaseSchema.parse({}), (set) => ({
idCounter: state.idCounter + 1,
}))
},
addPayment: (paymentInput: NewPayment) => {
const now = new Date().toISOString()
const payment: Payment = {
payment_id: `pay_${get().paymentCounter}`,
recipient: paymentInput.recipient,
amount: paymentInput.amount,
currency: paymentInput.currency ?? "USD",
status: "pending",
bounty_id: paymentInput.bounty_id,
issue_number: paymentInput.issue_number,
repository: paymentInput.repository,
idempotency_key: paymentInput.idempotency_key,
created_at: now,
updated_at: now,
}

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

return payment
},
findPaymentById: (paymentId: string) => {
return get().payments.find((payment) => payment.payment_id === paymentId)
},
findPaymentByIdempotencyKey: (idempotencyKey: string) => {
return get().payments.find(
(payment) => payment.idempotency_key === idempotencyKey,
)
},
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
})
},
transitionPayment: (
paymentId: string,
status: Exclude<PaymentStatus, "pending">,
) => {
const payment = get().payments.find(
(existingPayment) => existingPayment.payment_id === paymentId,
)
if (!payment) return undefined
if (terminalStatuses.has(payment.status)) return payment

const now = new Date().toISOString()
const updatedPayment: Payment = {
...payment,
status,
updated_at: now,
completed_at: status === "completed" ? now : payment.completed_at,
canceled_at: status === "canceled" ? now : payment.canceled_at,
}

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

return updatedPayment
},
}))
22 changes: 22 additions & 0 deletions lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,30 @@ 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(),
status: paymentStatusSchema,
bounty_id: z.string().optional(),
issue_number: z.number().int().positive().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(),
})
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>
33 changes: 33 additions & 0 deletions routes/payments/cancel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { paymentSchema } from "lib/db/schema"
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

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

const transitionPaymentResponseSchema = z.union([
z.object({
ok: z.literal(true),
payment: paymentSchema,
}),
z.object({
ok: z.literal(false),
error: z.string(),
}),
])

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

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

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

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

const transitionPaymentResponseSchema = z.union([
z.object({
ok: z.literal(true),
payment: paymentSchema,
}),
z.object({
ok: z.literal(false),
error: z.string(),
}),
])

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

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

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

const getPaymentResponseSchema = z.union([
z.object({
ok: z.literal(true),
payment: paymentSchema,
}),
z.object({
ok: z.literal(false),
error: z.string(),
}),
])

export default withRouteSpec({
methods: ["GET"],
jsonResponse: getPaymentResponseSchema,
})((req, ctx) => {
const url = new URL(req.url)
const paymentId = url.searchParams.get("payment_id")
if (!paymentId) {
return ctx.json({
ok: false,
error: "payment_id query parameter is required",
})
}

const payment = ctx.db.findPaymentById(paymentId)
if (!payment) {
return ctx.json({ ok: false, error: "payment not found" })
}

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

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

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

return ctx.json({
payments: ctx.db.listPayments(query),
})
})
45 changes: 45 additions & 0 deletions routes/payments/send.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { paymentSchema } from "lib/db/schema"
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().min(3).max(8).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 default withRouteSpec({
methods: ["POST"],
jsonBody: sendPaymentBodySchema,
jsonResponse: z.object({
ok: z.boolean(),
idempotent_replay: z.boolean(),
payment: paymentSchema,
}),
})(async (req, ctx) => {
const body = sendPaymentBodySchema.parse(await req.json())

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

const payment = ctx.db.addPayment({
...body,
currency: body.currency.toUpperCase(),
})

return ctx.json({ ok: true, idempotent_replay: false, payment })
})
Loading