如何限制在sailjs中的rest api中指定的更新 [英] how can I limit specify update filed in rest api in sailjs

查看:28
本文介绍了如何限制在sailjs中的rest api中指定的更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在sailsjs中使用restapi,我有一个用户模型:

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'
    } 

  },
};

我想公开一个rest api,例如更新.但我只想要休息 api 只允许更新电话 &电子邮件,而不是 real_name &is_verify .

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 .

我可以通过 beforeupdate 方法来限制提交的更新.

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();
    })
  }

但是这些代码行不会很优雅.有些人可能宁愿编写自己的 api 来覆盖它.

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

那么,在这种情况下,编写自己的 api 来覆盖其余 api 是否合适?

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 },

但没有运气.

推荐答案

当在模型实例上调用 toJSON 时,{protected: true} 选项会移除受保护的属性.

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.

您可以在此处查看所有 Waterline 验证:http://sailsjs.org//#/documentation/concepts/ORM/Validations.html

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

这篇关于如何限制在sailjs中的rest api中指定的更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆