4

How to generate multi level path parameters in feathers js like below :

api.com/category/catergoryId/subCatergory/subCatergoryId

rtvalluri
  • 557
  • 2
  • 6
  • 22

1 Answers1

9

The following is taken from this Feathers FAQ entry:

Normally we find that they actually aren't needed and that it is much better to keep your routes as flat as possible. For example something like users/:userId/posts is - although nice to read for humans - actually not as easy to parse and process as the equivalent /posts?userId=<userid> that is already supported by Feathers out of the box. Additionaly, this will also work much better when using Feathers through websocket connections which do not have a concept of routes at all.

However, nested routes for services can still be created by registering an existing service on the nested route and mapping the route parameter to a query parameter like this:

app.use('/posts', postService);
app.use('/users', userService);

// re-export the posts service on the /users/:userId/posts route
app.use('/users/:userId/posts', app.service('posts'));

// A hook that updates `data` with the route parameter
function mapUserIdToData(hook) {
  if(hook.data && hook.params.userId) {
    hook.data.userId = hook.params.userId;
  }
}

// For the new route, map the `:userId` route parameter to the query in a hook
app.service('users/:userId/posts').hooks({
  before: {
    find(hook) {
      hook.params.query.userId = hook.params.userId;
    },
    create: mapUserIdToData,
    update: mapUserIdToData,
    patch: mapUserIdToData
  }  
})

Now going to /users/123/posts will call postService.find({ query: { userId: 123 } }) and return all posts for that user.

Community
  • 1
  • 1
Daff
  • 43,734
  • 9
  • 106
  • 120
  • Isn't `postService` equivalent to app.service('posts')? If yes, then why did you use `app.service('posts')` instead of `postService`? – Shihab Jul 25 '19 at 09:25