diff --git a/example/crud.ts b/example/crud.ts new file mode 100644 index 0000000..97aae4e --- /dev/null +++ b/example/crud.ts @@ -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; + next(): string; +} + +@Provider({ provides: 'store' }) +class TodoStore { + private counter = 0; + private readonly todos: Map = 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): 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): 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): 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')); +} diff --git a/test/examples/crud.test.ts b/test/examples/crud.test.ts new file mode 100644 index 0000000..f97e236 --- /dev/null +++ b/test/examples/crud.test.ts @@ -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' }); + }); +});