How do I extend sails.js library

我只是一个虾纸丫 提交于 2019-12-13 03:21:30

问题


I would like to extend sailsjs to have something similar to rails strong params i.e.

req.params.limit(["email", "password", "password_confirmation"])

I have created this already as an add on, but I would like it to automatically attach to the request.params

Addon:

limit = function(limiters){
  params = this.all();
  self = Object();
  limiters.forEach(function(limiter){
    if(params[limiter]){
      self[limiter] = params[limiter]
    }
  return self;
}

request:

req.params.limit = limit;
req.params.limit(["email", "password"]);

How would I go about adding this to the framework as a module?


回答1:


i think you could just create a policy

// policies/limit.js
limit = function(limiters){
params = this.all();
self = Object();
limiters.forEach(function(limiter){
  if(params[limiter]){
    self[limiter] = params[limiter]
  }
return self;
}

module.exports = function limit (req, res, next) {
  req.params.limit = limit;
  req.params.limit(["email", "password"]);
  next();
};

then you can add the policy in your ./config/policies.js file. the example is for all controllers/actions. in the link above is the documentation on how to add it to specific actions.

// config/policies.js
module.exports.policies = { 
'*': 'limit'
};

EDIT: of course you can do the call to req.params.limit(...); in your controller if you don't want it static in your policy. policies are in general nothing more than express middlewares




回答2:


I see the use cases for this on controller actions, limiting possible searches and so on.

On the other hand: When you just want to your model not to take up undefined attributes found in a create request you could simply set schema to true for the corresponding model:

// models/example.js

module.exports = {
  schema: true,
  attributes: {...}
}

Setting it globally:

// config/models.js

module.exports.models = {
  schema: true,
  ...
}


来源:https://stackoverflow.com/questions/19240705/how-do-i-extend-sails-js-library

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