Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"route.path" doesn't match using nested routes #89

Open
isaiasvallejos opened this issue Aug 9, 2021 · 0 comments
Open

"route.path" doesn't match using nested routes #89

isaiasvallejos opened this issue Aug 9, 2021 · 0 comments
Assignees

Comments

@isaiasvallejos
Copy link

isaiasvallejos commented Aug 9, 2021

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.

See: expressjs/express#2879

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
@isaiasvallejos isaiasvallejos self-assigned this Aug 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant