简体   繁体   中英

SailsJS - Create versioned API without blueprint

I'm trying to figure out how to create a versionned API for my application. According to this issue https://github.com/balderdashy/sails/issues/322 , I have to use blueprint, but all blueprint is deactivated in my project (a wish from my boss).

I want to be able to have any URL like http://myapi.com/v1/my-custom-route , and so on for any version.

So far, the best way I've found is to duplicate all controller to something like v322AuthController.js and to map all routes like

'POST /v3.2.2/se-connecter'              : 'v322AuthController.perform_signin'

But I think that's an ugly trick. I'm currently using Nginx and all my code is versionned with git

Thank you if you have any idea

Kai23

you have to disable all blueprints? Than you have to write all your routes an our own.

If you don't want to duplicate your controllers you can try this:

config/routes.js

module.exports.routes = {

 'post /:apiversion/se-connecter' : {
    controller: 'AuthController',
    action: 'perform_signin',
    skipAssets: true
 }
....
}

So Sails passes all */se-connecter to the method "perform_signin" at your "AuthController". In your controller you have your api-version:

AuthController.js

module.exports = {
   perform_signin: function (req, res) {

      var apiversion = req.param('apiversion');

      if (apiversion === "0.2.0") {
         ....
      }
   }

}

My approach:

Create subfolder for your controllers as:

/controllers/v1/UserController.js
/controllers/v2/UserController.js

In your routes.js file, add as follow:

'POST /api/v2/user': 'v2/UserController.create',
'POST /api/v1/user': 'v2/UserController.create',

And in your policies.js, you can add middlewares like this:

  'v2/UserController': {
    'create': ['isAuthenticated','isAuthorized']
   }

My current sails' version is: 0.12.3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM