Nozbe / WatermelonDB

🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️
https://watermelondb.dev
MIT License
10.62k stars 600 forks source link

Model instance dependent json sanitisation #487

Closed davidkell closed 5 years ago

davidkell commented 5 years ago

We have a use case with the following parameters:

We want to validate and sanitise the JSON field using the sanitise content field. Is it possible to provide information on the kind to the sanitise content function for the content JSON field? (We couldn't find a way.)

A more concrete example:

export default class MyEntity extends Model {
  static table = 'myentity'

  @field('kind') kind

  @json('content', (content: object) => {
    // Here we want the validation function to depend on the kind.
    // Unfortunately this is not defined.
    validate(this.kind, content)
    return content
  })

}

(Another solution would be to have separate model for each distinct kind. Unfortunately, this would not work as we need to dynamically generate new kinds.)

rkrajewski commented 5 years ago

@davidkell Hi, indeed there is no way to do it, maybe only if data provided to sanitizer would contain a kind, but probably it's not what you look for.

Feel free to contribute - at first look, only what you need is to call sanitizer with this context.

here https://github.com/Nozbe/WatermelonDB/blob/master/src/decorators/json/index.js#L42 and here https://github.com/Nozbe/WatermelonDB/blob/master/src/decorators/json/index.js#L45

sanitizer.call(this, json)

but I haven't tested this solution.

davidkell commented 5 years ago

Thanks, will have a look at this.