Sails.js 如何修改路由以解释逗号分隔的 id 列表 [英] Sails.js how to modify routes to interprate comma separated list of ids
问题描述
根据一些 JSON API 规范,例如 http://jsonapi.org/format/#urls-individual-resources,服务器应将 GET 请求解释为/myResources/1,2,3,4,5.
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.
现在 Sails.js 路由器将其发送到 findOne
操作.
Right now the Sails.js router sends this to the findOne
action.
正确处理此问题的最佳方法是什么?
What is the best way to get this to be handled properly?
我认为理想情况下,路由器应该像解释 ?ids[1,2,3,4,5] 一样解释
/1,2,3,4,5
,但我意识到这可能不是小事.
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.
另一种选择是向所有 findOne
请求添加策略以检查 req.params('id')
是否包含逗号,然后将 id 列表重新格式化为查询字符串,然后重定向到 find
(这行得通吗?).将策略添加到每个控制器有点烦人.
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.
想法?
推荐答案
我认为这是您的建议,但这只是将其放在 findone.js 蓝图的顶部的问题.(或将此添加为策略).只需检查以确保它是一个字符串(以防您已经传递了一个数组.
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(',')
}
编辑:
对于任何实施者,请记住您的 findOne
政策将应用于此请求(请参阅评论).例如,假设您有一个 find
策略,该策略将一些参数应用于 req.options.where 以根据用户的权限过滤记录.在这种情况下将不适用!
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!
编辑除非你只是让你的路线将这些导向索引/查找路线.您可以将蓝图路由用于其他所有内容,但在 url 的key"部分中使用逗号的路由.
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.
这篇关于Sails.js 如何修改路由以解释逗号分隔的 id 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!