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
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,36 @@ 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 API

The fake payment API can be used to simulate sending and tracking bounty
payments.

### Send a payment

```http
POST /payments/send
Content-Type: application/json

{
"recipient": "maintainer@example.com",
"amount_usd": 10,
"bounty_id": "bounty_1",
"repository": "tscircuit/fake-algora",
"issue_number": 1,
"idempotency_key": "claim-1"
}
```

The `idempotency_key` can also be provided with the `Idempotency-Key` header.
Repeating the same key returns the original payment with
`idempotent_replay: true` instead of creating a duplicate.

### Other endpoints

- `GET /payments/list` lists payments. Optional query filters: `status`,
`recipient`, and `repository`.
- `GET /payments/get?payment_id=pay_0` returns one payment.
- `POST /payments/complete` marks a pending payment as completed.
- `POST /payments/cancel` marks a pending payment as canceled.
74 changes: 69 additions & 5 deletions lib/db/db-client.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
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) => ({
const initializer = combine(databaseSchema.parse({}), (set, get) => ({
addThing: (thing: Omit<Thing, "thing_id">) => {
set((state) => ({
things: [
Expand All @@ -21,4 +25,64 @@ const initializer = combine(databaseSchema.parse({}), (set) => ({
idCounter: state.idCounter + 1,
}))
},
createPayment: (
payment: Omit<
Payment,
"payment_id" | "status" | "created_at" | "completed_at" | "canceled_at"
>,
) => {
const existingPayment = payment.idempotency_key
? get().payments.find(
(currentPayment) =>
currentPayment.idempotency_key === payment.idempotency_key,
)
: undefined

if (existingPayment) {
return { payment: existingPayment, idempotent_replay: true }
}

const newPayment: Payment = {
...payment,
payment_id: `pay_${get().paymentIdCounter}`,
status: "pending",
created_at: new Date().toISOString(),
}

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

return { payment: newPayment, idempotent_replay: false }
},
updatePaymentStatus: (payment_id: string, status: PaymentStatus) => {
const currentPayment = get().payments.find(
(payment) => payment.payment_id === payment_id,
)

if (!currentPayment) {
return null
}

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

const updatedPayment = {
...currentPayment,
status,
...(status === "completed"
? { completed_at: new Date().toISOString() }
: { canceled_at: new Date().toISOString() }),
}

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

return updatedPayment
},
}))
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_usd: z.number(),
status: paymentStatusSchema,
bounty_id: z.string().optional(),
repository: z.string().optional(),
issue_number: z.number().optional(),
idempotency_key: z.string().optional(),
created_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([]),
paymentIdCounter: z.number().default(0),
payments: z.array(paymentSchema).default([]),
})
export type DatabaseSchema = z.infer<typeof databaseSchema>
42 changes: 42 additions & 0 deletions lib/payments/schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { paymentSchema, paymentStatusSchema } from "lib/db/schema"
import { z } from "zod"

export const sendPaymentBodySchema = z.object({
recipient: z.string().min(1),
amount_usd: z.number().positive(),
bounty_id: z.string().min(1).optional(),
repository: z.string().min(1).optional(),
issue_number: z.number().int().positive().optional(),
idempotency_key: z.string().min(1).optional(),
})

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

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

export const sendPaymentResponseSchema = paymentResponseSchema.extend({
idempotent_replay: z.boolean(),
})

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

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

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

export const paymentGetQuerySchema = z.object({
payment_id: z.string().min(1),
})
20 changes: 20 additions & 0 deletions routes/payments/cancel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import {
paymentOrErrorResponseSchema,
paymentStatusBodySchema,
} from "lib/payments/schemas"

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

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

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

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

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

return ctx.json({ payment })
})
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 { withRouteSpec } from "lib/middleware/with-winter-spec"
import {
paymentGetQuerySchema,
paymentOrErrorResponseSchema,
} from "lib/payments/schemas"

export default withRouteSpec({
methods: ["GET"],
queryParams: paymentGetQuerySchema,
jsonResponse: paymentOrErrorResponseSchema,
})((req, ctx) => {
const payment = ctx.db.payments.find(
(currentPayment) => currentPayment.payment_id === req.query.payment_id,
)

if (!payment) {
return ctx.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,
paymentStatusQuerySchema,
} from "lib/payments/schemas"

export default withRouteSpec({
methods: ["GET"],
queryParams: paymentStatusQuerySchema,
jsonResponse: paymentListResponseSchema,
})((req, ctx) => {
const { status, recipient, repository } = req.query
const payments = ctx.db.payments.filter((payment) => {
if (status && payment.status !== status) return false
if (recipient && payment.recipient !== recipient) return false
if (repository && payment.repository !== repository) return false
return true
})

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

export default withRouteSpec({
methods: ["POST"],
jsonBody: sendPaymentBodySchema,
jsonResponse: sendPaymentResponseSchema,
})(async (req, ctx) => {
const paymentRequest = await req.json()
const idempotencyHeader = req.headers.get("idempotency-key") ?? undefined
const result = ctx.db.createPayment({
...paymentRequest,
idempotency_key: paymentRequest.idempotency_key ?? idempotencyHeader,
})

return ctx.json(result)
})
Loading