Filter only allowed params to model

Hi guys!

Just wrote one simple trait which could be useful to someone out there, so here it is…

When creatingm saving or merging data to a model instance you need to clean object from keys that are not inside that table schema.
This trait will clean object from all keys that are not allowed in schema.

app/Models/Traits/ClearParams.js

'use strict'

class ClearParams {
    async register(Model, customOptions = {}) {

        let validColumns = await Model.query().columnInfo()
        validColumns = Object.keys(validColumns)

        Model.clearParams = function (params) {
            for (let key in params) {
                if (!~validColumns.indexOf(key)) delete params[key]
            }
            return params
        }

    }
}

module.exports = ClearParams

assign this trait to model you want
for example: app/Models/User.js

'use strict'

const Model = use('Model')

class User extends Model {    
    static boot() {
        super.boot()
        this.addTrait('ClearParams')
    }
}

module.exports = User

To use it when, for example, creating new user:
inside any controller or whatever

const allParams = {
    firstName: 'Somebody',
    lastName: 'Something',
    imNotAllowedHere: 'example...',
    anotherKeyThatSchemaDontHave: 'something else...'
}

const allowedParams = User.clearParams(allParams)
await User.create(allowedParams)

btw. columnInfo() gives a lot information, so even basic validation rules could be created from this data… :slight_smile:

4 Likes

For those who were looking for a solution like this but find a bug in Adonis, a possible solution is to manually clear the fields. First you need to define the fields in Model:

class User extends Model {
  static boot() {
    super.boot();

    this.addTrait('ClearParams');
  }

  static get columns() {
    return ['id', 'email', 'password']
  }
}

Then, adapt the original Trait:

'use strict'

class ClearParams {
  async register(Model, customOptions = {}) {
    let validColumns = Object.keys(Model.columns)

    Model.clearParams = function (params) {
      for (let key in params) {
        if (!~validColumns.indexOf(key)) delete params[key]
      }
      return params
    }
  }
}

module.exports = ClearParams
1 Like