-
Notifications
You must be signed in to change notification settings - Fork 1
"route.path" doesn't match using nested routes #89
Description
I'm having some problems using the route.path parameter on propsToLog using nested routes with Express Router. Searching the internet I saw that this is an issue of the Express package itself.
Using express router with nested routes, for example:
// routes/users.js
const usersRouter = Router({ mergeParams: true });
usersRouter.get('/:id', (request, response) => {
console.log(request.route.path) // "/:id" (instead of "/users/:id")
return response.status(200).json([/* list of users */])
})
// app.js
const app = express();
app.use('/users', usersRoutes)I would like to have a property on log that has the value /users/:id but, using route.path, I always get the value :id which can be mixed with any other route that has a /:id route, since they will log the same value. This ends up making it very difficult to filter the logs by route.
My suggestion: Can we create an own property of Escriba to handle this?
Using route.params we can create a value that uses the request.originalUrl and can create the same value as route.path does but full with parent paths/suffixes.
Example code (suggestion by @asheba):
const reverseMapParamValuesToKeys = params => {
const entries = Object.entries(params);
return entries.reduce(
(map, [key, value]) => ({ ...map, [value]: `:${key}` }),
{},
);
};
const paramValuesToKeys = reverseMapParamValuesToKeys(request.params);
const originalUrl = request.originalUrl || '';
const splittedUrl = originalUrl.split('/');
const replaceWithParams = splittedUrl.map(
urlPart => paramValuesToKeys[urlPart] || urlPart,
);
const path = replaceWithParams.join('/');
const pathWithoutQueryString = path.split('?')[0];
const routePath = pathWithoutQueryString;
console.log(routePath) // /users/:id