From 1188d7f0d852b2f518388fa4f4a4220c43d74d60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E9=93=AD=E9=94=8B?= Date: Thu, 14 May 2026 22:31:28 +0800 Subject: [PATCH] Add fake payment API --- README.md | 55 +++++++++++-- lib/db/db-client.ts | 73 +++++++++++++++-- lib/db/schema.ts | 24 ++++++ routes/payments/cancel.ts | 19 +++++ routes/payments/complete.ts | 19 +++++ routes/payments/get.ts | 19 +++++ routes/payments/list.ts | 26 ++++++ routes/payments/send.ts | 34 ++++++++ tests/routes/payments/send.test.ts | 125 +++++++++++++++++++++++++++++ 9 files changed, 383 insertions(+), 11 deletions(-) create mode 100644 routes/payments/cancel.ts create mode 100644 routes/payments/complete.ts create mode 100644 routes/payments/get.ts create mode 100644 routes/payments/list.ts create mode 100644 routes/payments/send.ts create mode 100644 tests/routes/payments/send.test.ts diff --git a/README.md b/README.md index 824427a..4549ce1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,51 @@ -# Template API Project +# Fake Algora API -This is a template project with best-practice modules: -- Winterspec for defining the API -- bun testing -- Zustand store with zod definition for database state +Small Winterspec API for simulating Algora-style bounty payments in tests and +development. + +## Payments + +### Send a payment + +`POST /payments/send` + +```json +{ + "recipient": "github:octocat", + "amount_cents": 1000, + "currency": "USD", + "memo": "Bounty payout", + "idempotency_key": "issue-1-octocat" +} +``` + +Returns a fake payment with `status: "sent"`. Reusing the same +`idempotency_key` returns the original payment with `idempotent_replay: true` +instead of creating a duplicate. + +### List payments + +`GET /payments/list` + +Optional filters: + +- `recipient` +- `status` + +### Get a payment + +`GET /payments/get?payment_id=0` + +Returns a single payment, or `null` when it does not exist. + +### Complete or cancel a payment + +`POST /payments/complete` + +```json +{ + "payment_id": "0" +} +``` + +`POST /payments/cancel` accepts the same body shape. diff --git a/lib/db/db-client.ts b/lib/db/db-client.ts index e525e65..88610fc 100644 --- a/lib/db/db-client.ts +++ b/lib/db/db-client.ts @@ -1,9 +1,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 { hoist } from "zustand-hoist" import { combine } from "zustand/middleware" +import { createStore } from "zustand/vanilla" + +import { + type Payment, + type PaymentStatus, + type Thing, + databaseSchema, +} from "./schema.ts" export const createDatabase = () => { return hoist(createStore(initializer)) @@ -11,7 +15,7 @@ export const createDatabase = () => { export type DbClient = ReturnType -const initializer = combine(databaseSchema.parse({}), (set) => ({ +const initializer = combine(databaseSchema.parse({}), (set, get) => ({ addThing: (thing: Omit) => { set((state) => ({ things: [ @@ -21,4 +25,61 @@ const initializer = combine(databaseSchema.parse({}), (set) => ({ idCounter: state.idCounter + 1, })) }, + sendPayment: ( + payment: Omit< + Payment, + "payment_id" | "status" | "created_at" | "updated_at" | "completed_at" + >, + ) => { + const existingPayment = + payment.idempotency_key && + get().payments.find( + (item) => item.idempotency_key === payment.idempotency_key, + ) + + if (existingPayment) return existingPayment + + const timestamp = new Date().toISOString() + const paymentToCreate: Payment = { + ...payment, + currency: payment.currency.toUpperCase(), + payment_id: get().paymentIdCounter.toString(), + status: "sent", + created_at: timestamp, + updated_at: timestamp, + } + + set((state) => ({ + payments: [...state.payments, paymentToCreate], + paymentIdCounter: state.paymentIdCounter + 1, + })) + + return paymentToCreate + }, + getPayment: (payment_id: string) => { + return get().payments.find((payment) => payment.payment_id === payment_id) + }, + updatePaymentStatus: (payment_id: string, status: PaymentStatus) => { + const timestamp = new Date().toISOString() + let updatedPayment: Payment | undefined + + set((state) => ({ + payments: state.payments.map((payment) => { + if (payment.payment_id !== payment_id) return payment + + updatedPayment = { + ...payment, + status, + updated_at: timestamp, + completed_at: + status === "completed" + ? payment.completed_at ?? timestamp + : payment.completed_at, + } + return updatedPayment + }), + })) + + return updatedPayment + }, })) diff --git a/lib/db/schema.ts b/lib/db/schema.ts index 8377516..5c44f9c 100644 --- a/lib/db/schema.ts +++ b/lib/db/schema.ts @@ -9,8 +9,32 @@ export const thingSchema = z.object({ }) export type Thing = z.infer +export const paymentStatusSchema = z.enum([ + "sent", + "completed", + "canceled", + "failed", +]) +export type PaymentStatus = z.infer + +export const paymentSchema = z.object({ + payment_id: z.string(), + recipient: z.string(), + amount_cents: z.number().int().positive(), + currency: z.string(), + memo: z.string().optional(), + idempotency_key: z.string().optional(), + status: paymentStatusSchema, + created_at: z.string(), + updated_at: z.string(), + completed_at: z.string().optional(), +}) +export type Payment = z.infer + 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 diff --git a/routes/payments/cancel.ts b/routes/payments/cancel.ts new file mode 100644 index 0000000..1d950b5 --- /dev/null +++ b/routes/payments/cancel.ts @@ -0,0 +1,19 @@ +import { paymentSchema } from "lib/db/schema" +import { withRouteSpec } from "lib/middleware/with-winter-spec" +import { z } from "zod" + +export default withRouteSpec({ + methods: ["POST"], + jsonBody: z.object({ + payment_id: z.string(), + }), + jsonResponse: z.object({ + payment: paymentSchema.nullable(), + }), +})(async (req, ctx) => { + const { payment_id } = await req.json() + + return ctx.json({ + payment: ctx.db.updatePaymentStatus(payment_id, "canceled") ?? null, + }) +}) diff --git a/routes/payments/complete.ts b/routes/payments/complete.ts new file mode 100644 index 0000000..260668a --- /dev/null +++ b/routes/payments/complete.ts @@ -0,0 +1,19 @@ +import { paymentSchema } from "lib/db/schema" +import { withRouteSpec } from "lib/middleware/with-winter-spec" +import { z } from "zod" + +export default withRouteSpec({ + methods: ["POST"], + jsonBody: z.object({ + payment_id: z.string(), + }), + jsonResponse: z.object({ + payment: paymentSchema.nullable(), + }), +})(async (req, ctx) => { + const { payment_id } = await req.json() + + return ctx.json({ + payment: ctx.db.updatePaymentStatus(payment_id, "completed") ?? null, + }) +}) diff --git a/routes/payments/get.ts b/routes/payments/get.ts new file mode 100644 index 0000000..10473e1 --- /dev/null +++ b/routes/payments/get.ts @@ -0,0 +1,19 @@ +import { paymentSchema } from "lib/db/schema" +import { withRouteSpec } from "lib/middleware/with-winter-spec" +import { z } from "zod" + +export default withRouteSpec({ + methods: ["GET"], + queryParams: z.object({ + payment_id: z.string(), + }), + jsonResponse: z.object({ + payment: paymentSchema.nullable(), + }), +})((req, ctx) => { + const payment_id = new URL(req.url).searchParams.get("payment_id") ?? "" + + return ctx.json({ + payment: ctx.db.getPayment(payment_id) ?? null, + }) +}) diff --git a/routes/payments/list.ts b/routes/payments/list.ts new file mode 100644 index 0000000..e9bd2bf --- /dev/null +++ b/routes/payments/list.ts @@ -0,0 +1,26 @@ +import { paymentSchema, paymentStatusSchema } from "lib/db/schema" +import { withRouteSpec } from "lib/middleware/with-winter-spec" +import { z } from "zod" + +export default withRouteSpec({ + methods: ["GET"], + queryParams: z.object({ + recipient: z.string().optional(), + status: paymentStatusSchema.optional(), + }), + jsonResponse: z.object({ + payments: z.array(paymentSchema), + }), +})((req, ctx) => { + const url = new URL(req.url) + const recipient = url.searchParams.get("recipient") + const status = url.searchParams.get("status") + + return ctx.json({ + payments: ctx.db.payments.filter((payment) => { + if (recipient && payment.recipient !== recipient) return false + if (status && payment.status !== status) return false + return true + }), + }) +}) diff --git a/routes/payments/send.ts b/routes/payments/send.ts new file mode 100644 index 0000000..af396a1 --- /dev/null +++ b/routes/payments/send.ts @@ -0,0 +1,34 @@ +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_cents: z.number().int().positive(), + currency: z.string().length(3).default("USD"), + memo: z.string().optional(), + idempotency_key: z.string().optional(), +}) + +export default withRouteSpec({ + methods: ["POST"], + jsonBody: sendPaymentBodySchema, + jsonResponse: z.object({ + payment: paymentSchema, + idempotent_replay: z.boolean(), + }), +})(async (req, ctx) => { + const paymentRequest = sendPaymentBodySchema.parse(await req.json()) + const existingPayment = + paymentRequest.idempotency_key && + ctx.db.payments.find( + (payment) => payment.idempotency_key === paymentRequest.idempotency_key, + ) + + const payment = ctx.db.sendPayment(paymentRequest) + + return ctx.json({ + payment, + idempotent_replay: Boolean(existingPayment), + }) +}) diff --git a/tests/routes/payments/send.test.ts b/tests/routes/payments/send.test.ts new file mode 100644 index 0000000..ded91af --- /dev/null +++ b/tests/routes/payments/send.test.ts @@ -0,0 +1,125 @@ +import { expect, test } from "bun:test" +import { getTestServer } from "tests/fixtures/get-test-server" + +test("sends and stores a fake payment", async () => { + const { axios } = await getTestServer() + + const { data } = await axios.post("/payments/send", { + recipient: "github:octocat", + amount_cents: 1000, + currency: "usd", + memo: "Bounty payout", + }) + + expect(data).toMatchObject({ + idempotent_replay: false, + payment: { + payment_id: "0", + recipient: "github:octocat", + amount_cents: 1000, + currency: "USD", + memo: "Bounty payout", + status: "sent", + }, + }) + + const listResponse = await axios.get("/payments/list") + expect(listResponse.data.payments).toHaveLength(1) +}) + +test("defaults payment currency to USD", async () => { + const { axios } = await getTestServer() + + const { data } = await axios.post("/payments/send", { + recipient: "github:octocat", + amount_cents: 250, + }) + + expect(data.payment.currency).toBe("USD") +}) + +test("deduplicates retries by idempotency key", async () => { + const { axios } = await getTestServer() + + const payload = { + recipient: "github:octocat", + amount_cents: 1500, + idempotency_key: "issue-1-octocat", + } + + const firstResponse = await axios.post("/payments/send", payload) + const secondResponse = await axios.post("/payments/send", payload) + + expect(secondResponse.data).toMatchObject({ + idempotent_replay: true, + payment: { + payment_id: firstResponse.data.payment.payment_id, + idempotency_key: "issue-1-octocat", + }, + }) + + const listResponse = await axios.get("/payments/list") + expect(listResponse.data.payments).toHaveLength(1) +}) + +test("gets and filters payments", async () => { + const { axios } = await getTestServer() + + await axios.post("/payments/send", { + recipient: "github:octocat", + amount_cents: 500, + }) + await axios.post("/payments/send", { + recipient: "github:hubot", + amount_cents: 750, + }) + + const getResponse = await axios.get("/payments/get", { + params: { payment_id: "1" }, + }) + expect(getResponse.data.payment).toMatchObject({ + payment_id: "1", + recipient: "github:hubot", + }) + + const filterResponse = await axios.get("/payments/list", { + params: { recipient: "github:octocat" }, + }) + expect(filterResponse.data.payments).toHaveLength(1) + expect(filterResponse.data.payments[0].recipient).toBe("github:octocat") +}) + +test("completes and cancels payments", async () => { + const { axios } = await getTestServer() + + await axios.post("/payments/send", { + recipient: "github:octocat", + amount_cents: 500, + }) + await axios.post("/payments/send", { + recipient: "github:hubot", + amount_cents: 750, + }) + + const completeResponse = await axios.post("/payments/complete", { + payment_id: "0", + }) + expect(completeResponse.data.payment).toMatchObject({ + payment_id: "0", + status: "completed", + }) + expect(completeResponse.data.payment.completed_at).toBeTruthy() + + const cancelResponse = await axios.post("/payments/cancel", { + payment_id: "1", + }) + expect(cancelResponse.data.payment).toMatchObject({ + payment_id: "1", + status: "canceled", + }) + + const completedPayments = await axios.get("/payments/list", { + params: { status: "completed" }, + }) + expect(completedPayments.data.payments).toHaveLength(1) +})