examples: annotate examples
[nit.git] / lib / popcorn / examples / mongodb / example_mongodb.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014-2015 Alexandre Terrasa <alexandre@moz-code.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 module example_mongodb is example
18
19 import popcorn
20 import mongodb
21 import template
22
23 class UserList
24 super Handler
25
26 var db: MongoDb
27
28 redef fun get(req, res) do
29 var users = db.collection("users").find_all(new JsonObject)
30
31 var tpl = new Template
32 tpl.add """
33 <h1>Users</h1>
34
35 <h2>Add a new user</h2>
36 <form action="/" method="POST">
37 <input type="text" name="login" />
38 <input type="password" name="password" />
39 <input type="submit" value="save" />
40 </form>
41
42 <h2>All users</h2>
43 <table>"""
44 for user in users do
45 tpl.add """<tr>
46 <td>{{{user["login"] or else "null"}}}</td>
47 <td>{{{user["password"] or else "null"}}}</td>
48 </tr>"""
49 end
50 tpl.add "</table>"
51 res.html(tpl)
52 end
53
54 redef fun post(req, res) do
55 var json = new JsonObject
56 json["login"] = req.post_args["login"]
57 json["password"] = req.post_args["password"]
58 db.collection("users").insert(json)
59 res.redirect("/")
60 end
61 end
62
63 var mongo = new MongoClient("mongodb://localhost:27017/")
64 var db = mongo.database("mongo_example")
65
66 var app = new App
67 app.use("/", new UserList(db))
68 app.listen("localhost", 3000)