Elysia
Build a REST API with Elysia and jcell. Elysia is a performant Bun-first web framework with end-to-end type safety.
Setup​
bun add @sajjadbzn/jcell elysia
Complete API​
app.ts
import { Elysia, t as elysiaT } from 'elysia'
import { createDB, schema, t, fileAdapter } from '@sajjadbzn/jcell'
// ── Schema ─────────────────────────────────────────────────────────────────
const taskSchema = schema({
id: t.id(),
title: t.string(),
completed: t.boolean().default(false),
priority: t.enum(['low', 'medium', 'high'] as const),
createdAt: t.date().default(() => new Date()),
})
// ── Database setup ─────────────────────────────────────────────────────────
const db = createDB({ adapter: fileAdapter({ path: './data' }) })
const tasks = db.collection('tasks', taskSchema)
// ── Elysia app ─────────────────────────────────────────────────────────────
const app = new Elysia()
.get('/tasks', async () => {
return await tasks.find()
})
.post(
'/tasks',
async ({ body }) => {
try {
const task = await tasks.insert({
title: body.title,
priority: body.priority ?? 'medium',
})
return task
} catch (err) {
return { error: (err as Error).message }
}
},
{
body: elysiaT.Object({
title: elysiaT.String(),
priority: elysiaT.Optional(
elysiaT.Union([
elysiaT.Literal('low'),
elysiaT.Literal('medium'),
elysiaT.Literal('high'),
]),
),
}),
},
)
.patch('/tasks/:id', async ({ params, body }) => {
const count = await tasks.update({ id: params.id }, body)
if (count === 0) return { error: 'Not found' }
return await tasks.first({ id: params.id })
})
.delete('/tasks/:id', async ({ params }) => {
const count = await tasks.delete({ id: params.id })
if (count === 0) return { error: 'Not found' }
return { deleted: true }
})
.listen(3000)
console.log(`Elysia + jcell running at http://localhost:${app.server?.port}`)
Run It​
bun run app.ts
Type Safety​
Elysia's validation integrates with Elysia's built-in type system for request validation:
.post(
'/tasks',
async ({ body }) => {
// body.title is typed as string
// body.priority is typed as 'low' | 'medium' | 'high' | undefined
const task = await tasks.insert({
title: body.title,
priority: body.priority,
})
return task
},
{
body: elysiaT.Object({
title: elysiaT.String(),
priority: elysiaT.Optional(
elysiaT.Union([
elysiaT.Literal('low'),
elysiaT.Literal('medium'),
elysiaT.Literal('high'),
]),
),
}),
},
)