feat(example): in-memory CRUD with query and JSON/urlencoded bodies

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-06-28 13:28:42 -05:00
1 parent 9050a7e5d9
commit 3842271c4d
2 files changed
+119

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
import {
createApp, Provider, Route,
Get, Post, Put, Patch, Delete,
Module, needs, param, query, body, NotFound,
} from '../src/index';
interface Todo { id: string; title: string; done: boolean }
interface Store {
todos: Map<string, Todo>;
next(): string;
}
@Provider({ provides: 'store' })
class TodoStore {
private counter = 0;
private readonly todos: Map<string, Todo> = new Map();
provide(): { store: Store } {
const store: Store = {
todos: this.todos,
next: () => String(++this.counter),
};
return { store };
}
}
@Route('/todos')
class TodoController {
@Get('/')
list(@needs('store') store: Store, @query('done') done: string | undefined): Todo[] {
const all = [...store.todos.values()];
if (done !== undefined) {
const flag = done === 'true';
return all.filter((t) => t.done === flag);
}
return all;
}
@Get('/:id')
get(@needs('store') store: Store, @param('id') id: string): Todo {
const todo = store.todos.get(id);
if (!todo) throw new NotFound(`todo ${id} not found`);
return todo;
}
@Post('/')
create(@needs('store') store: Store, @body() data: Record<string, unknown>): Todo {
const id = store.next();
const todo: Todo = { id, title: String(data.title ?? ''), done: false };
store.todos.set(id, todo);
return todo;
}
@Put('/:id')
replace(@needs('store') store: Store, @param('id') id: string, @body() data: Record<string, unknown>): Todo {
if (!store.todos.has(id)) throw new NotFound(`todo ${id} not found`);
const todo: Todo = { id, title: String(data.title ?? ''), done: Boolean(data.done ?? false) };
store.todos.set(id, todo);
return todo;
}
@Patch('/:id')
merge(@needs('store') store: Store, @param('id') id: string, @body() data: Record<string, unknown>): Todo {
const todo = store.todos.get(id);
if (!todo) throw new NotFound(`todo ${id} not found`);
const updated: Todo = {
id,
title: 'title' in data ? String(data.title) : todo.title,
done: 'done' in data ? Boolean(data.done) : todo.done,
};
store.todos.set(id, updated);
return updated;
}
@Delete('/:id')
remove(@needs('store') store: Store, @param('id') id: string): { deleted: string } {
if (!store.todos.has(id)) throw new NotFound(`todo ${id} not found`);
store.todos.delete(id);
return { deleted: id };
}
}
@Module({ mountpoint: '/api', providers: [TodoStore], controllers: [TodoController] })
class TodoModule {}
export const app = createApp({ modules: [TodoModule] });
if (require.main === module) {
app.listen(3300).then(() => console.log('green-tea crud on http://localhost:3300'));
}
+28
View File
@@ -0,0 +1,28 @@
import { describe, it, expect, afterAll } from 'vitest';
import { app } from '../../example/crud';
let base: string; let server: any;
const url = (p: string) => `${base}${p}`;
afterAll(() => server?.close());
describe('crud example', () => {
it('supports create / read / update / delete', async () => {
server = await app.listen(0); base = `http://127.0.0.1:${(server.address() as any).port}`;
const created = await fetch(url('/api/todos'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: 'a' }) }).then((r) => r.json() as Promise<{ id: string; title: string; done: boolean }>);
expect(created).toMatchObject({ title: 'a' });
const id = created.id;
expect(await fetch(url(`/api/todos/${id}`)).then((r) => r.json())).toMatchObject({ title: 'a' });
await fetch(url(`/api/todos/${id}`), { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ done: true }) });
expect(await fetch(url(`/api/todos/${id}`)).then((r) => r.json())).toMatchObject({ done: true });
const list = await fetch(url('/api/todos')).then((r) => r.json());
expect(Array.isArray(list)).toBe(true);
const del = await fetch(url(`/api/todos/${id}`), { method: 'DELETE' });
expect(del.status).toBe(200);
expect((await fetch(url(`/api/todos/${id}`))).status).toBe(404);
});
it('accepts urlencoded form bodies', async () => {
const res = await fetch(url('/api/todos'), { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'title=form' });
expect(await res.json()).toMatchObject({ title: 'form' });
});
});