Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested model validation #478

Closed
vladshcherbin opened this issue Aug 12, 2017 · 3 comments
Closed

Nested model validation #478

vladshcherbin opened this issue Aug 12, 2017 · 3 comments

Comments

@vladshcherbin
Copy link
Contributor

I tried to use insertGraph method, but I'm not sure how to handle validation errors for nested models.

For example

Person.query()
  .insertGraph({
    firstName: 'Sylvester',
    lastName: 'Stallone',
    children: [{
      firstName: 'Sage'
    }]
  })

If children model has required field for lastName and input value is not provided, I'd expect a nested error with children.0.lastName.

For current workaround I take input data, validate and then use model to save so validation is handled outside of the model.

This also led me to thoughts, if validation logic belongs to a model or a request layer. Shall we validate data first and then use model to save it or leave validation to model and improve nested validation.

I'm interested in recommended way of doing this since nested data validation is common and current ways of solving this.

@vladshcherbin
Copy link
Contributor Author

vladshcherbin commented Aug 12, 2017

Same question for a different scenario: you want to validate model with different rule sets (for example, different rules for insert and update).

One way is to use patch method which omits required fields check, but there are sure another use cases, where you need to validate different fields. I can think of an example where your validation rules depend on a received field value or current user.

If validation is handled outside of the model, you can validate incoming data with different rule sets and use model just to insert or update after. Not sure, if this is possible with current model layer validation.

@koskimas
Copy link
Collaborator

After trying to implement this in objection, I think the best way to achieve this is by also adding your relations to jsonSchema. It will lead to some duplicate validation in some cases, but it's still the cleanest way to get this done since Ajv can already give those nested errors. Adding the logic to objection is really difficult.

@vladshcherbin
Copy link
Contributor Author

@koskimas yeah, I ended up by moving validation away from model level and never had any issues :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants