Sails.js how to modify routes to interprate comma

2019-08-07 09:27发布

According to some JSON API specifciations, such as http://jsonapi.org/format/#urls-individual-resources, the server should interpret a GET request to /myResources/1,2,3,4,5.

Right now the Sails.js router sends this to the findOne action.

What is the best way to get this to be handled properly?

I think ideally the router should interpret /1,2,3,4,5 in the same way it would interpret ?ids[1,2,3,4,5], but I realize this may not be trivial.

Another option is to add a policy to all findOne requests to check if req.params('id') has commas and then reformat the list of ids to a query string and then redirect to find (would this work?). Kind of annoying to add the policy to every controller.

Thoughts?

1条回答
仙女界的扛把子
2楼-- · 2019-08-07 09:48

I think this was your suggestion, but its simply a matter placing this in the top of the findone.js blueprint. (or adding this as a policy). Just check to make sure its a string (incase your already passing an array.

if(typeof req.params.id === "string"){
    req.params.id = req.params.id.split(',')
}

EDIT:

For anyone implementing, keep in mind that your findOne policies will be applied to this request (see comments). For example, suppose you have a policy for find that applies some parameters to req.options.where to filter records based on the user's permissions. This won't be applied in this case!

EDIT Unless you just make your routes direct these to the index/find route. You could use blueprints routes for everything else, but those with commas in the "key" portion of the url.

查看更多
登录 后发表回答