Skip to content

Posts API Example

A complete, single-file example demonstrating how to declare a typed table schema and expose read, create, update, and delete endpoints.

Terminal window
import { backend } from "@layeron/core"
import { db, table, text, integer, rawSql } from "@layeron/modules"
const app = backend({
project: "layeron-posts",
compatibilityDate: "2026-05-23",
})
const database = db({
name: "main",
schema: {
posts: table({
id: text().primaryKey(),
title: text().notNull(),
body: text().notNull(),
status: text().notNull().default("draft"),
createdAt: integer().notNull().default(rawSql("(unixepoch())")),
}),
},
})
app.use(database)
app.get("/api/posts", async () => {
const { results: posts } = await database
.table("posts")
.orderBy("createdAt", "desc")
.limit(20)
.all()
return Response.json({ posts })
})
app.get("/api/posts/:id", async (request) => {
const pathSegments = new URL(request.url).pathname.split("/")
const id = pathSegments[3]
const post = await database
.table("posts")
.where({ id: id })
.maybeOne()
if (!post) {
return Response.json({ error: "Post not found" }, { status: 404 })
}
return Response.json({ post })
})
app.post("/api/posts", async (request) => {
const input = await request.json() as { title: string; body: string }
const post = {
id: crypto.randomUUID(),
title: input.title,
body: input.body,
}
await database.table("posts").insert(post).run()
return Response.json({ post }, { status: 201 })
})
app.patch("/api/posts/:id", async (request) => {
const pathSegments = new URL(request.url).pathname.split("/")
const id = pathSegments[3]
const input = await request.json() as { title?: string; body?: string; status?: string }
await database
.table("posts")
.update(input)
.where({ id: id })
.run()
const post = await database.table("posts").where({ id: id }).one()
return Response.json({ post })
})
app.delete("/api/posts/:id", async (request) => {
const pathSegments = new URL(request.url).pathname.split("/")
const id = pathSegments[3]
await database.table("posts").delete().where({ id: id }).run()
return Response.json({ ok: true })
})
export default app

Run it with the Layeron CLI dev server and send requests to the exposed /api/posts endpoints.