how can I limit specify update filed in rest api in sailjs

99封情书 提交于 2019-12-25 14:49:11

问题


I'm using restapi in sailsjs , I have a user model:

module.exports = {

  schema: true,

  attributes: {

    username : { type: 'string' },    

    real_name : { type: 'string' },

    encrypted_password: {
      type: 'string'
    },

    id_card : { type: 'string' },

    is_verify : { type : 'boolean' } ,

    email : { type: 'string' },

    phone : {
      type: 'string'
    } 

  },
};

I would like to expose a rest api , such as update. But I only want rest api to just allow update phone & email, rather than real_name & is_verify .

I can do it in beforeupdate method to limit the update filed.

beforeUpdate: function(values, cb) {
    // accessing the function defined above the module.exports
    FilterUpdateField(function() {
      cb();
    })
  }

But these lines of code would NOT be elegant. Some may rather write their own api to override it.

So, Would it be properly to write my own api to override the rest api in this situation?

I asked a related question here. Here I have try to use :

is_verify : { type : 'boolean' ,protected:true} ,

    email : { type: 'string',protected:true },

but without luck.


回答1:


The {protected: true} option removes the protected attribute when toJSON is called on a model instance.

The only way to do what you want, is filtering the results that will arrive to the update method. I would do this in the Model:

beforeUpdate: function(values, next) {
  if(values.email) delete values.email;
  if(values.is_verify) delete values.is_verify;
  // if whatever the delete whatever
  return next();
}

I don't think that this way is the most elegant, but it's clean and easy to understand what's happening there.

You can check all the Waterline validations here: http://sailsjs.org/#/documentation/concepts/ORM/Validations.html



来源:https://stackoverflow.com/questions/27360945/how-can-i-limit-specify-update-filed-in-rest-api-in-sailjs

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