简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM