Merge: Popcorn valid
## Quick and easy validation framework for Json inputs
Validators can be used in Popcorn apps to valid your json inputs before
data processing and persistence.
Here an example with a Book management app. We use an ObjectValidator to validate
the books passed to the API in the `POST /books` handler.
~~~nit
import popcorn
import serialization
# Serializable book representation.
class Book
super Jsonable
# Book ISBN
var isbn: String
# Book title
var title: String
# Book image (optional)
var img: nullable String
# Book price
var price: Float
end
class BookValidator
super ObjectValidator
redef init do
add new ISBNField("isbn")
add new StringField("title", min_size=1, max_size=255)
add new StringField("img", required=false)
add new FloatField("price", min=0.0, max=999.0)
end
end
class BookHandler
super Handler
# Insert a new Book
redef fun post(req, res) do
var validator = new BookValidator
if not validator.validate(req.body) then
res.json_error(validator.validation, 400)
return
end
# TODO data persistence
end
end
~~~
Pull-Request: #2240
Reviewed-by: Jean Privat <jean@pryen.org>