-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
127 lines (106 loc) · 2.62 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
'use strict';
var Hapi = require('hapi');
var Boom = require('boom');
var path = require('path');
var _ = require('lodash');
var MongoClient = require('mongodb').MongoClient;
// Connection URL
var url = 'mongodb://localhost:27017/tizen';
// Create a server with a host and port
var server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 8000,
});
var states = {
cloudy: 'nuage',
stormy: 'orage',
rainy: 'pluie',
sunny: 'soleil',
};
var defineState = function(total) {
if (total < 0) {
return states.stormy;
}
if (total < 500) {
return states.rainy;
}
if (total < 1000) {
return states.cloudy;
}
return states.sunny;
};
// Add the route
server.route({
method: 'GET',
path: '/me',
handler: function (request, reply) {
var collection = request.server.db.collection('users');
if (!request.query.token) {
return reply(Boom.unauthorized('No valid token found, please register at: /register'));
}
var user = collection.findOne({token: request.query.token}).then(function(user) {
if (!user) {
return reply(Boom.unauthorized('No user found, please register at: /register'));
}
var total = _.random(-500, 2000);
var accountState = defineState(total);
return reply({
msg: 'hello me with token ' + request.query.token,
username: user.username,
accountState: '/img/' + accountState + '.jpg',
total: total,
});
});
},
});
server.route({
method: 'POST',
path: '/register',
handler: function(request, reply) {
var collection = request.server.db.collection('users');
collection.insertOne(request.payload).then(function() {
reply.redirect('/me?token=' + request.payload.token);
});
},
});
server.register(require('inert'), function(err) {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/register',
handler: {
file: path.resolve(__dirname, 'index.html'),
},
});
server.route({
method: 'GET',
path: '/img/{param*}',
handler: {
directory: {
path: path.resolve(__dirname, 'meteo'),
},
},
});
// Start the server
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
if (err) {
throw err;
}
server.db = db;
console.log('Connected succesfully to server');
server.on('stop', function() {
console.log('Closed succesfully connection to server');
db.close();
});
server.start(function(err) {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
});
});