4f89f5b50312d25d16cba6d7d5604a2da90d63ea
[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 import popcorn
18 import mongodb
19 import template
20
21 class UserList
22 super Handler
23
24 var db: MongoDb
25
26 redef fun get(req, res) do
27 var users = db.collection("users").find_all(new JsonObject)
28
29 var tpl = new Template
30 tpl.add """
31 <h1>Users</h1>
32
33 <h2>Add a new user</h2>
34 <form action="/" method="POST">
35 <input type="text" name="login" />
36 <input type="password" name="password" />
37 <input type="submit" value="save" />
38 </form>
39
40 <h2>All users</h2>
41 <table>"""
42 for user in users do
43 tpl.add """<tr>
44 <td>{{{user["login"] or else "null"}}}</td>
45 <td>{{{user["password"] or else "null"}}}</td>
46 </tr>"""
47 end
48 tpl.add "</table>"
49 res.html(tpl)
50 end
51
52 redef fun post(req, res) do
53 var json = new JsonObject
54 json["login"] = req.post_args["login"]
55 json["password"] = req.post_args["password"]
56 db.collection("users").insert(json)
57 res.redirect("/")
58 end
59 end
60
61 var mongo = new MongoClient("mongodb://localhost:27017/")
62 var db = mongo.database("mongo_example")
63
64 var app = new App
65 app.use("/", new UserList(db))
66 app.listen("localhost", 3000)