Skip to Content

Publish an API

An OpenAPI spec and reference page generated from your validators, signed outbound webhooks, and HTTP caching.

Install

npm i @dapplelight/signet-server @dapplelight/signet-lib hono zod

Serve OpenAPI from your validators

server/app.ts
import { Hono } from "hono"
import { apiDoc, serveOpenApi } from "@dapplelight/signet-server/http/openapi"
import { zValidator } from "@dapplelight/signet-server/http/validate"
import { create, get, health, sync } from "./notes"
import { Id, Note, NoteInput } from "./schemas"

const app = new Hono()

app.get("/notes/:id", apiDoc({ summary: "Get a note", tags: ["Notes"], response: Note }), zValidator("param", Id), get)
app.post("/notes", apiDoc({ responses: { 201: { description: "Created", schema: Note } } }), zValidator("json", NoteInput), create)
app.get("/health", apiDoc({ security: false }), health) // public
app.post("/internal/sync", apiDoc(false), sync)          // not in the spec

serveOpenApi(app, {
  info: { title: "Notes API", version: "1.0.0" },
  security: { session: { cookieName: "sid" }, apiKey: { prefix: "app" } },
})

GET /openapi.json returns OpenAPI 3.1 and GET /docs an HTML reference.

Register outbound webhooks

server/db/webhooks.ts
import { webhookTables } from "@dapplelight/signet-db/columns/sqlite" // or /columns/pg
import { createWebhooks } from "@dapplelight/signet-db/webhooks"
import { db } from "./index"

export const { webhookEndpoints, webhookDeliveries } = webhookTables()

export const webhooks = createWebhooks(db, { endpoints: webhookEndpoints, deliveries: webhookDeliveries })
server/app.ts
import { webhookRoutes } from "@dapplelight/signet-server/http/webhooks"
import { requireStoredSession } from "@dapplelight/signet-server/auth/hono"
import { webhooks } from "./db/webhooks"
import { sessionOpts } from "./session"

app.use("/api/webhooks/*", requireStoredSession(sessionOpts))
app.route("/api/webhooks", webhookRoutes({ webhooks, owner: (c) => c.get("session").payload.sub }))

Queue an event with the change that caused it

server/routes/orders.ts
import { db } from "../db"
import { orders } from "../db/schema"
import { webhooks } from "../db/webhooks"

export async function createOrder(orgId: string, order: typeof orders.$inferInsert) {
  await db.batch([
    (tx) => tx.insert(orders).values(order),
    ...(await webhooks.statements({ owner: orgId, type: "order.created", data: order })),
  ])
}

Deliver from a cron

worker/index.ts
import { drainOutbox } from "@dapplelight/signet-db"
import { WEBHOOK_TOPIC } from "@dapplelight/signet-db/webhooks"
import { db } from "../server/db"
import { webhooks } from "../server/db/webhooks"
import { queue } from "./queue"

await drainOutbox(db, { send: (m) => (m.topic === WEBHOOK_TOPIC ? webhooks.send(m) : queue.send(m)) })

Verify on the receiving side

receiver/hooks.ts
import { Hono } from "hono"
import { verifyWebhook } from "@dapplelight/signet-lib/webhooks"
import { WEBHOOK_SECRET } from "./env"

const app = new Hono()

app.post("/hooks/orders", async (c) => {
  const body = await c.req.text() // the raw text: re-serialised JSON does not verify
  if (!(await verifyWebhook(WEBHOOK_SECRET, c.req.raw.headers, body))) return c.text("bad signature", 401)
  const id = c.req.header("webhook-id") // the same on every retry: dedupe on it
  return c.body(null, 204)
})

Cache read endpoints

server/app.ts
import { cachedResponse, httpCache } from "@dapplelight/signet-server/http/cache"
import { requireStoredSession } from "@dapplelight/signet-server/auth/hono"
import { buildStats, listPlans, myOrders, orgId } from "./handlers"
import { kv } from "./kv"

app.get("/plans", httpCache({ maxAge: 300, staleWhileRevalidate: 60 }), listPlans)
app.get("/me/orders", requireStoredSession(sessionOpts), httpCache({ private: true }), myOrders)
app.get("/stats", (c) =>
  cachedResponse(c, { kv, freshSeconds: 60, staleSeconds: 600, varyBy: orgId(c) }, async () => c.json(await buildStats())),
)

Next