-
Notifications
You must be signed in to change notification settings - Fork 5
Group options
The full group options
object with their default values looks like this:
{
"prefix": "/", // url prefix shared by all routes in this group
"middleware": [], // middleware shared by all routes in this group
"namespace": "", // namespace shared by all named routes in this group
"patterns": {}, // regex patterns shared by all route params in this group
"meta": {} // additional meta data to associate to all routes in this group
}
Note that all fields are optional, and any combination of fields can be used.
A string that is the common uri to shared with all routes in this group.
router.group({ prefix: '/api' }, (router) => {
// all routes defined in here will have their uris prefixed by /api.
});
Note that the above example is functionally equivalent to the /api
group in the quickstart example.
An array of middleware shared with all routes in this group.
router.group({
middleware: [
(req, res, next) => {
next();
},
(req, res, next) => {
next();
}
]
}, (router) => {
// all routes defined in here will inherit the above middleware.
});
A string that will be prefixed to any named routes in this group.
router.group({
namespace: 'api.'
}, (router) => {
router.get({ uri: '/users', name: 'getUsers' }, (req, res) => {
// this route can generate a url by supplying "api.getUsers" to the router.url() function.
});
});
Note 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.group({
prefix: '/users',
patterns: {
userId: /^\d+$/
}
}, (router) => {
router.get('/{userId}', (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) => {
});
});