tests/sav: Update tests results
[nit.git] / lib / popcorn / pop_json.nit
index db80ebe..8a5ba58 100644 (file)
@@ -55,6 +55,8 @@
 # ~~~
 module pop_json
 
+import json
+import meta
 import pop_handlers
 import pop_validation
 
@@ -146,7 +148,7 @@ redef class Handler
        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
@@ -158,4 +160,29 @@ redef class Handler
        #
        # 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, plain, pretty: nullable Bool) do
+               header["Content-Type"] = media_types["json"].as(not null)
+               if json == null then
+                       send(null, status)
+               else
+                       send(json.serialize_to_json(plain or else true, pretty or else false), 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