Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 711
Benedikt Avatar asked Jun 16 '15 12:06

Benedikt


2 Answers

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',
like image 118
Benedikt Avatar answered Nov 04 '22 08:11

Benedikt


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']: { ... }.

like image 41
nbkhope Avatar answered Nov 04 '22 08:11

nbkhope