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
55 changes: 50 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -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.
73 changes: 67 additions & 6 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 { 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))
}

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,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
},
}))
24 changes: 24 additions & 0 deletions lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,32 @@ export const thingSchema = z.object({
})
export type Thing = z.infer<typeof thingSchema>

export const paymentStatusSchema = z.enum([
"sent",
"completed",
"canceled",
"failed",
])
export type PaymentStatus = z.infer<typeof paymentStatusSchema>

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<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>
19 changes: 19 additions & 0 deletions routes/payments/cancel.ts
Original file line number Diff line number Diff line change
@@ -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,
})
})
19 changes: 19 additions & 0 deletions routes/payments/complete.ts
Original file line number Diff line number Diff line change
@@ -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,
})
})
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 { 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,
})
})
26 changes: 26 additions & 0 deletions routes/payments/list.ts
Original file line number Diff line number Diff line change
@@ -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
}),
})
})
34 changes: 34 additions & 0 deletions routes/payments/send.ts
Original file line number Diff line number Diff line change
@@ -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),
})
})
Loading