Rocket: Schema validation

Created on 27 Dec 2016  路  2Comments  路  Source: SergioBenitez/Rocket

What would be the preferred way to plug in something like valico to validate JSON body data against a schema before it is serialized into a struct that is returned to its route?

Would it be better to validate the struct after it has been passed to the route by rocket?

question

Most helpful comment

This is the sort of thing FromData was tailor-made for. To integrate valico, I would:

  1. Create a new type. Let's call it ValidJSON.

      struct ValidJSON<T: Deserialize>(T);
    
  2. Implement FromData for ValidJSON, likely by calling contrib::JSON::from_data in the implementation, doing the validation, and returning an appropriate Outcome depending on the results.

You'd then use the type in a route as follows:

#[post("/", data = "<val>")]
fn (val: ValidJSON<T>) ...

All 2 comments

This is the sort of thing FromData was tailor-made for. To integrate valico, I would:

  1. Create a new type. Let's call it ValidJSON.

      struct ValidJSON<T: Deserialize>(T);
    
  2. Implement FromData for ValidJSON, likely by calling contrib::JSON::from_data in the implementation, doing the validation, and returning an appropriate Outcome depending on the results.

You'd then use the type in a route as follows:

#[post("/", data = "<val>")]
fn (val: ValidJSON<T>) ...

Ah, exactly what I was looking for. Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

klnusbaum picture klnusbaum  路  4Comments

incker picture incker  路  3Comments

GoRustafari picture GoRustafari  路  3Comments

sphinxc0re picture sphinxc0re  路  3Comments

shssoichiro picture shssoichiro  路  4Comments