# ~~~
module pop_json
+import json
+import meta
import pop_handlers
import pop_validation
fun deserialize_body(req: HttpRequest, res: HttpResponse): nullable BODY do
var body = req.body
var deserializer = new JsonDeserializer(body)
- var form = deserializer.deserialize(body)
+ var form = deserializer.deserialize(body_type)
if not form isa BODY or deserializer.errors.not_empty then
res.json_error("Bad input", 400)
return null
#
# Define it in each sub handlers depending on the kind of objects sent in request bodies.
type BODY: Serializable
+
+ private var body_type: String is lazy do return (new GetName[BODY]).to_s
+end
+
+redef class HttpResponse
+
+ # Write data as JSON and set the right content type header.
+ fun json(json: nullable Serializable, status: nullable Int) do
+ header["Content-Type"] = media_types["json"].as(not null)
+ if json == null then
+ send(null, status)
+ else
+ send(json.to_json, status)
+ end
+ end
+
+ # Write error as JSON.
+ #
+ # Format: `{"message": message, "status": status}`
+ fun json_error(message: String, status: Int) do
+ var obj = new JsonObject
+ obj["status"] = status
+ obj["message"] = message
+ json(obj, status)
+ end
end