sylvainpolletvillard / ObjectModel

Strong Dynamically Typed Object Modeling for JavaScript
http://objectmodel.js.org
MIT License
467 stars 30 forks source link

Assertion that is based on the value of another property #86

Closed gotjoshua closed 6 years ago

gotjoshua commented 6 years ago

We have a model that requires the comments property to be non-empty if status property == 'blocked'

Is it possible to make an assertion for one prop that depends on another?

sylvainpolletvillard commented 6 years ago

Something like that ?

const MyModel = ObjectModel({ 
  comments: ArrayModel(String),
  status: String
}).assert(o => o.status !== 'blocked' || o.comments.length > 0, 
  "requires the comments property to be non-empty if status property == 'blocked'")
gotjoshua commented 6 years ago

nearly perfect!

I went with:

const MyModel = ObjectModel({ 
  comments: ArrayModel(String),
  status: String
}).assert(o => o.status !== 'blocked' || !! o.comments, 
  "requires the comments property to be non-empty if status property == 'blocked'")

as undefined comments have no length (maybe also because I am using String as my comments type - why do you suggest ArrayModel(String) ? )

Thanks once again!

sylvainpolletvillard commented 6 years ago

I did not know what the type of your variable was, I guessed it was an array because you used the plural form, which is a popular convention. If it is an optional string, change the definition to comments: [String]