From 782c85ea5667d440428749bcee15b6cd50ac7d5a Mon Sep 17 00:00:00 2001 From: =?utf8?q?Alexis=20Laferri=C3=A8re?= Date: Tue, 10 Nov 2015 08:20:58 -0500 Subject: [PATCH] contrib/tnitter: add REST interface MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Alexis Laferrière --- contrib/tnitter/src/action.nit | 32 +++++++++++++++++++++++++++++++- contrib/tnitter/src/model.nit | 3 +++ contrib/tnitter/src/tnitter.nit | 3 ++- 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/contrib/tnitter/src/action.nit b/contrib/tnitter/src/action.nit index 261e842..e40e309 100644 --- a/contrib/tnitter/src/action.nit +++ b/contrib/tnitter/src/action.nit @@ -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` @@ -241,3 +242,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.to_json_string + return response + end + + # Format not recognized + var error = new Error("Bad Request") + var response = new HttpResponse(400) + response.body = error.to_json_string + return response + end +end diff --git a/contrib/tnitter/src/model.nit b/contrib/tnitter/src/model.nit index 241baf9..68aeb6e 100644 --- a/contrib/tnitter/src/model.nit +++ b/contrib/tnitter/src/model.nit @@ -18,9 +18,12 @@ module model import md5 +import serialization # A single post (or Tnit) class Post + serialize + # The author var user: String diff --git a/contrib/tnitter/src/tnitter.nit b/contrib/tnitter/src/tnitter.nit index 490fc07..35d2432 100644 --- a/contrib/tnitter/src/tnitter.nit +++ b/contrib/tnitter/src/tnitter.nit @@ -58,7 +58,8 @@ var user_group = opts.drop.value if user_group != null then user_group.drop_privileges # Complete server config -vh.routes.add new Route(null, new Tnitter) +vh.routes.add new Route("/rest/", new TnitterREST) +vh.routes.add new Route(null, new TnitterWeb) # Run print "Launching server on http://{interfac} ..." -- 1.7.9.5