-
Notifications
You must be signed in to change notification settings - Fork 0
Route options
The full route options object with their default values looks like this:
{
"method": "get", // the HTTP method for this route definition
"uri": "/", // the url fragment for this route definition
"middleware": [], // the middleware specific to this route definition
"name": "", // a name to associate to this route definition
"patterns": {}, // any patterns specific to this route definition
"meta": {} // any additional meta data to associate to this route definition
}Note that all fields are optional, and any combination of fields can be used.
A string that specifies the HTTP method to route to. If not supplied, the default method is "get". Also,
specifying the method in the options object can be avoided by using the router.{method} shortcuts
router.route({ method: 'get', uri: '/api' }, (req, res) => {
});
// the default method is "get"
router.route({ uri: '/api' }, (req, res) => {
});
// the default method is "get", and if a string is used instead of an object, that string becomes the uri option.
router.route('/api', (req, res) => {
});
// using router.{method} prefills the options object with the correct method.
router.get({ uri: '/api' }, (req, res) => {
});
// shortcut to the above
router.get('/api', (req, res) => {
});A string that specifies the url location to route to.
router.route({ method: 'post', uri: '/create' }, (req, res) => {
});An array of middleware specific to this route definition.
router.route({
uri: '/users',
middleware: [
(req, res, next) => {
next();
},
(req, res, next) => {
next();
}
]
}, (req, res) => {
});A string that will be used to identify this route. Used in generating urls to a specific route.
router.get({
uri: '/user/{userId}',
name: 'getUser',
patterns: {
userId: /^\d+$/
}
}, (req, res) => {
});
const url = router.url('getUser', { userId: 1});
// url will equal /user/1Note that route names can be useful for other purposes, such as defining the operationIds in swagger/openapi specs.
An object whose key=>value pairs are actually route params => regex patterns. Routes using these route params will only be matched if the param successfully matches its regex pattern.
router.route({
uri: '/users/{}',
patterns: {
userId: /^\d+$/
}
}, (req, res) => {
// this route will only be matched if userId is a number.
});An object that can contain arbitrary custom data. This is useful if you wish to associate some data with each route definition outside of the common options provided above.
const mapActionToHandler = (action, routeDescription, routeOptions) => {
// routeDescription.meta will contain {foo: 'bar', baz: 'qux'};
// routeOptions.meta will contain {baz: 'qux'}
return action;
};
const router = createRouter(app, mapActionToHandler);
router.group({
prefix: '/api',
meta: {
foo: 'bar'
},
}, (router) => {
router.get({
uri: '/users',
meta: {
baz: 'qux'
}
}, (req, res) => {
});
});