How to maintain multiple API versions in sails.js

可紊 提交于 2019-12-04 03:35:01

You can get away with putting your controllers in subdirectories as in your example, because nested controllers are fully supported by Sails. However, nested models are not fully supported because of the ambiguity they would cause (see this comment on the matter). If you put two model files both named Cat.js in separate subfolders, they'll collide and the second one will overwrite the first in memory when Sails lifts.

That's sort of an academic point though, since you'll need some way to distinguish between your two model versions anyway in code. That is, in your v1 controller you'll want to make sure you're referencing your v1 Cat model, and likewise for v2. The simplest solution would be to go with a scheme like you have in your example, but add a suffix to your models (or at least everything after v1):

api/
|-- controllers/
|---- v1/
|------ CatController.js
|---- v2/
|------ CatController.js
|-- models/
|---- v1/
|------ Cat.js
|---- v2/
|------ Cat_v2.js

The subfolder for the models will be ignored by Sails, so to make sure your blueprints work the way you want, you can add a _config property to your controllers to force them to use the correct model.

api/controllers/v1/CatController.js:

module.exports = {
  _config: {
    model: 'cat'
  },
  ...
}

api/controllers/v2/CatController.js:

module.exports = {
  _config: {
    model: 'cat_v2'
  },
  ...
}

Update (for Sails 1.0)

The usage of _config in a controller is no longer valid in Sails 1.0. Instead, you can use the parseBlueprintOptions config function to set which model a blueprint operates on, e.g.:

parseBlueprintOptions: function(req) {

  // Get the default query options.
  var queryOptions = req._sails.hooks.blueprints.parseBlueprintOptions(req);

  // Add the _v2 suffix to the `using` property.
  queryOptions.using = queryOptions.using + '_v2';

  return queryOptions;

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