← All tasksNode.js · Junior

Route with parameters

Express and Fastify routers describe routes with patterns: /users/:id/posts/:postId. Write matchRoute(pattern, path) that returns an object of params when the path matches ({ id: "7", postId: "99" }), or null when it doesn't.

Static parts must match exactly, and so must the number of segments. A trailing / and a query string (?page=2) don't prevent a match, and param values are decoded (my%20report.pdf → my report.pdf).

Tests (6)

  1. expect(matchRoute('/users/:id', '/users/42')).toEqual({ id: '42' });
  2. expect(matchRoute('/users/:id/posts/:postId', '/users/7/posts/99')).toEqual({ id: '7', postId: '99' });
  3. expect(matchRoute('/health', '/health')).toEqual({});
  4. expect(matchRoute('/users/:id', '/posts/42')).toBe(null);
    expect(matchRoute('/users/:id', '/users/42/posts')).toBe(null);
    expect(matchRoute('/users/:id', '/users')).toBe(null);
  5. expect(matchRoute('/users/:id', '/users/42/')).toEqual({ id: '42' });
    expect(matchRoute('/search/:q', '/search/hello?page=2')).toEqual({ q: 'hello' });
  6. expect(matchRoute('/files/:name', '/files/my%20report.pdf')).toEqual({ name: 'my report.pdf' });