Merge: Popcorn valid
authorJean Privat <jean@pryen.org>
Mon, 8 Aug 2016 22:23:50 +0000 (18:23 -0400)
committerJean Privat <jean@pryen.org>
Mon, 8 Aug 2016 22:23:50 +0000 (18:23 -0400)
commitd40583163eb3e099ade392e78149e94e40cdf5dd
tree5acf3eb5cf9bae7114da16f86ee7a356bc3c93ab
parent87e81cc48a865f13fb0f424dc713000871a1e191
parent32b43264fc1488d59a8f1a1a35382ab449aa809b
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>