A simple fast and functional route parser, for Javascript in Node and the browser. Its api is inspired by EventEmitter2, but is implemented in a more functional way, don't rely in 'this' keyword.
yarn add @funjs/emitter
or
npm install --save @funjs/emitter
const Emitter = require('@funjs/emitter');
const emitter = Emitter();
emitter.on('users/:action=(insert|update)/:id', ({ action, id }, data) => {
console.log(`action: ${action}`);
console.log(`id: ${id}`);
console.log(`data: ${JSON.stringify(data)}`);
});
emitter.emit('users/insert/1', { id: 1, name: 'Joe', age: 33 });
// action: insert
// id: 1
// data: {"id":1,"name":"Joe","age":33}
const Emitter = require('@funjs/emitter');
const emitter = Emitter();
emitter.on('*/*/:id', (e, data) => {
console.log(`event: ${JSON.stringify(e)}`);
console.log(`data: ${JSON.stringify(data)}`);
});
emitter.emit('users/insert/1', { id: 1, name: 'Joe', age: 33 });
// event: {"0":"users","1":"insert","id":"1"}
// data: {"id":1,"name":"Joe","age":33}
const Emitter = require('@funjs/emitter');
const emitter = Emitter({ delimiter: '.', namedSection: '$' });
emitter.on('users.$action=(insert|update).id', ({ action, id }, data) => {
console.log(`action: ${action}`);
console.log(`id: ${id}`);
console.log(`data: ${JSON.stringify(data)}`);
});
emitter.emit('users.insert.1', { id: 1, name: 'Joe', age: 33 });
// action: insert
// id: 1
// data: {"id":1,"name":"Joe","age":33}
Example | Description |
---|---|
:name |
a named parameter to capture from the route up to / , ? , or end of string |
* |
a splat to capture from the route up to ? or end of string |
:name=(a|b|c) |
a named parameter group that doesn't have to be part of the query. Can contain nested optional groups, params, and splats |
anything else | free form literals |
Some examples:
/some/:thing
/users/:id/comments/:comment/rating/:rating
/*/foo/*
/books/:section=(Romance|Horror)/:title
- Basic API
- Customizables delimeters and named segment symbols
- Reverse Matching
- Implement all features of EventEmitter2
- Emplement a "RethinkDBish" query API