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

只谈情不闲聊 提交于 2019-12-12 02:38:47

问题


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 some rest api , but I only allow findOne method , and what's more :

I DON'T want the result contains id_card , because it's kind of private info.

Sailsjs doesn't has beforeFindOne or afterFindOne.

what can I do?

Besides:

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 two situations?


回答1:


For your first question:

I DON'T want the result contains id_card , because it's kind of private info.

You should simply add the option protected: true to the model attribute, as in:

attributes:{
  id_card : { 
    type: 'string',
    protected: true 
  }, 
}

For your second question: I don't really know a way to protect an attribute to update rather than the beforeUpdate you are already using.

PD: you should probably create different threads for each question you have.



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

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