@g1suite/api-framework
v0.1.0
Published
Minimal Node HTTP router with method-aware dispatch, dynamic params, and a directory loader.
Readme
@g1suite/api-framework
Minimal Node HTTP router with method-aware dispatch, dynamic params, and a directory loader.
Router Basics
- Create a router and register routes:
import { createRouter } from '@g1suite/api-framework';
const router = createRouter();
router.get('/hello', (req, res, ctx) => ctx?.json({ ok: true }));- Dynamic params with
:param:
router.get('/users/:id', (req, res, ctx) => {
ctx?.json({ id: ctx?.params.id });
});- Middleware:
router.use((req, res, next) => { /* auth, logging, etc */ next(); });RequestContext
Handlers receive a ctx with:
url,methodparamsfrom dynamic segmentsqueryas an object (multi-values grouped)json(data, status?)andtext(body, status?)
Loader
Auto-register route modules from a directory:
import { loadRoutesFromDir } from '@g1suite/api-framework';
await loadRoutesFromDir(router, 'src/routes');- File
src/routes/hello.ts->GET /hello - Nested
src/routes/users/list.js->GET /users/list - Bracket params
src/routes/users/[id].ts->/users/:id - Named method exports (
GET,POST,PUT,PATCH,DELETE,OPTIONS) are registered per method; otherwise a default export is treated asGET.
Method Fallback
- Static routes:
GETfallback when onlyGETis registered. - Dynamic routes:
GETfallback is allowed when the exact method is not found.
Server Example
import http from 'node:http';
import { createRouter, loadRoutesFromDir } from '@g1suite/api-framework';
const router = createRouter();
await loadRoutesFromDir(router, 'src/routes');
http.createServer(router.listener()).listen(3000);