feat: end-to-end example demonstrating the four core ideas

This commit is contained in:
chrnx committed 2026-06-26 01:04:24 -05:00
1 parent 221a230270
commit 04c8b3a743
3 files changed
+70

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
````markdown
# green-tea example
```bash
npx ts-node example/server.ts # or: npm run build && node dist/example/server.js
curl -H 'x-token: u1' http://localhost:3000/api/users/9
```
Demonstrates: typed context contract, graph-derived order, `app.inspect()`,
and a logger plugin that observes the bus without touching the chain.
````
+43
View File
@@ -0,0 +1,43 @@
import { createApp, Provider, Step, Route, Get, Module, Transformer, JsonTransformer, Unauthorized, Plugin } from '../src/index';
interface User { id: string; name: string }
@Provider({ provides: 'db' })
class Database {
provide() {
const users: Record<string, User> = { u1: { id: 'u1', name: 'Diego' } };
return { db: { find: (token: string) => users[token] ?? null } };
}
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx: { db: { find: (t: string) => User | null }; req: { headers: Record<string, string> } }) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('invalid token');
return { user };
}
}
@Route('/users')
class UserController {
@Get('/:id')
@Transformer(JsonTransformer)
getUser(ctx: { user: User; params: { id: string } }) {
return { requested: ctx.params.id, you: ctx.user };
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const logger: Plugin = (api) => {
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`));
};
export const app = createApp({ modules: [ApiModule], plugins: [logger] });
if (require.main === module) {
console.log('chain for /api/users/:id ->', app.inspect('/api/users/:id'));
app.listen(3000).then(() => console.log('green-tea on http://localhost:3000'));
}