How do I namespace my api in sails.js like so /api/v1?

独自空忆成欢 提交于 2020-01-01 05:38:47

问题


I want to namespace my api requests to /api/v1/ Maybe later some also to api/v2/. How can I do this efficiently in sails.js?


回答1:


There is three ways of doing this.

1st: blueprints

http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.blueprints.html how to create a global route prefix in sails?

prefix: '/api'

or restPrefix: '/api'

how to create a global route prefix in sails?

2nd: in each controller adding

_config: { prefix: '/api/v2' }

3rd: configure it in the routes

http://sailsjs.org/#!/documentation/concepts/Routes

'/api/v2/': 'FooController',



回答2:


Whereas other frameworks allow you to nest a block or closure, you can't do so in Sails. My approach is to use a variable that holds the prefix and apply it (after evaluating the string) to each route object key as such:

const prefix = '/my/api/v2';

module.exports = {
  [`GET ${prefix}/where/ever/you/want`]: { ... },

  [`POST ${prefix}/some/where/nice`]: { ... },
}

The above uses string interpolation with ES6. If you do not have that, just use string concatenation: ['GET ' + prefix + '/where/ever']: { ... }.



来源:https://stackoverflow.com/questions/30867333/how-do-i-namespace-my-api-in-sails-js-like-so-api-v1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!