@e22m4u/js-trie-router
A pure ES-module of the Node.js HTTP router that uses the
Trie for routing.
- Uses path-to-regexp syntax.
- Supports path parameters.
- Parses JSON-body automatically.
- Parses a query string and a
cookie
header. - Supports
preHandler
and postHandler
hooks. - Asynchronous request handler.
Installation
npm install @e22m4u/js-trie-router
To load an ES-module set "type": "module"
in the package.json
or use the .mjs
extension.
Overview
A basic "Hello world." example.
import http from 'http';
import {TrieRouter} from '../src/index.js';
import {HTTP_METHOD} from '../src/route.js';
const server = new http.Server();
const router = new TrieRouter();
router.defineRoute({
method: HTTP_METHOD.GET,
path: '/',
handler(ctx) {
return 'Hello world!';
},
});
server.on('request', router.requestHandler);
server.listen(3000, 'localhost');
RequestContext
The first parameter of a route handler is a RequestContext
instance.
container: ServiceContainer
is an instance of the ServiceContainerreq: IncomingMessage
is a native request from the http
moduleres: ServerResponse
is a native response from the http
moduleparams: ParsedParams
is a key-value object of path parametersquery: ParsedQuery
is a key-value object of a parsed query stringheaders: ParsedHeaders
is a key-value object of request headerscookie: ParsedCookie
is a key-value object of a parsed cookie
headermethod: string
is a request method in lower case like get
, post
etc.path: string
is a request pathname with a query stringpathname: string
is a request pathname without a query string
Here are possible values of RequestContext properties.
router.defineRoute({
method: 'get',
path: '/users/:id',
handler(ctx) {
console.log(ctx.req);
console.log(ctx.res);
console.log(ctx.params);
console.log(ctx.query);
console.log(ctx.headers);
console.log(ctx.cookie);
console.log(ctx.method);
console.log(ctx.path);
console.log(ctx.pathname);
},
});
Sending response
Return values of a route handler will be sent as described below.
value | content-type |
---|
string | text/plain |
number | application/json |
boolean | application/json |
object | application/json |
Buffer | application/octet-stream |
Stream | application/octet-stream |
Here is an example of a JSON response.
router.defineRoute({
handler(ctx) {
return {foo: 'bar'};
},
});
If the ServerResponse
has been sent manually, then a return
value of the route handler will be ignored.
router.defineRoute({
handler(ctx) {
res.statusCode = 404;
res.setHeader('content-type', 'text/plain; charset=utf-8');
res.end('404 Not Found', 'utf-8');
},
});
Route hooks
A route definition allows you to set following hooks:
preHandler
is executed before a route handler.postHandler
is executed after a route handler.
If the preHandler
hook returns a value other than undefined
or null
, it will be used as the server response.
router.defineRoute({
preHandler(ctx) {
return 'Are you authenticated?';
},
handler(ctx) {
return 'Hello world!';
},
});
A return value of the route handler will be passed as the second
argument to the preHandler
hook.
router.defineRoute({
handler(ctx) {
return 'Hello world!';
},
preHandler(ctx, data) {
return data.toUpperCase();
},
});
Global hooks
A Router
instance allows you to set following global hooks:
preHandler
is executed before each route handler.postHandler
is executed after each route handler.
The addHook
method of a Router
instance accepts a hook name as the first
parameter and the hook function as the second.
router.addHook('preHandler', (ctx) => {
});
router.addHook('postHandler', (ctx, data) => {
});
Similar to a route hook, if a global hook returns a value other than
undefined
or null
, that value will be used as the server response.
Debug
Set environment variable DEBUG=jsTrieRouter*
before start.
DEBUG=jsPathTrie* npm run test
Testing
npm run test
Contribution
- Bug fixes.
- Grammar correction.
- Documentation improvements.
- Vulnerability fixes.
License
MIT