Merge: model: introduce model_json
[nit.git] / contrib / tnitter / src / action.nit
index 261e842..60ee384 100644 (file)
@@ -18,6 +18,7 @@
 module action
 
 import nitcorn
+import json::serialization
 
 import model
 import database
@@ -31,7 +32,7 @@ redef class Session
 end
 
 # Main Tnitter Action
-class Tnitter
+class TnitterWeb
        super Action
 
        # Header on pages served by this `Action`
@@ -81,6 +82,9 @@ class Tnitter
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
+       <script>
+               {{{javascript_header or else ""}}}
+       </script>
 </head>
 <body>
 
@@ -92,6 +96,9 @@ class Tnitter
 </body>
 </html>"""
 
+       # Custom JavaScript code added within a `<script>` block to each page
+       var javascript_header: nullable Writable = null is writable
+
        redef fun answer(request, turi)
        do
                # Get existing session
@@ -241,3 +248,32 @@ class Tnitter
                return response
        end
 end
+
+# Tnitter RESTful interface
+class TnitterREST
+       super Action
+
+       redef fun answer(request, turi)
+       do
+               if turi == "/list" then
+                       # list?from=1&count=2 -> Error | Array[Post]
+
+                       var from = request.int_arg("from") or else 0
+                       var count = request.int_arg("count") or else 8
+
+                       var db = new DB.open(tnitter_db_path)
+                       var posts = db.list_posts(from, count)
+                       db.close
+
+                       var response = new HttpResponse(200)
+                       response.body = posts.serialize_to_json
+                       return response
+               end
+
+               # Format not recognized
+               var error = new Error("Bad Request")
+               var response = new HttpResponse(400)
+               response.body = error.serialize_to_json
+               return response
+       end
+end