-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
140 lines (122 loc) · 3.63 KB
/
server.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
128
129
130
131
132
133
134
135
136
137
138
139
140
var http = require("http");
var fs = require("fs");
var dispatcher = require('httpdispatcher');
var file = "pmm.db";
var exists = fs.existsSync(file);
if (!exists) {
console.log("creating database file.");
fs.openSync(file, "w");
}
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(file);
const PORT = 8080;
/**
* Create the database
*/
db.serialize(function() {
if(!exists) {
db.run("CREATE TABLE users ( id integer primary key asc, userid integer not null, totalratio float not null)");
}
});
/**
* Dispatcher method to determine which url is being requested.
*/
function handleRequest(req, res) {
try {
console.log(req.url);
dispatcher.dispatch(req, res);
} catch(err) {
console.log(err);
}
}
/**
* Main page is requested, send them a cool message
*/
dispatcher.onGet("/", function(req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end("PersonalMoneyManager API");
});
/**
* Main POST call to get all ratio's from user
*
* userid - id number unqiue to one user
* totalratio - the ratio of purchases / household size
*/
dispatcher.onPost("/", function(req, res) {
// get the data passed from request
var data = JSON.parse(req.body);
// assure all required fields are set and valid
if (data.userid != null && data.totalratio != null) {
console.log("userid:" + data.userid + ";totalratio:" + data.totalratio);
}
db.serialize(function() {
db.run("INSERT OR REPLACE INTO users (id, userid, totalratio) VALUES ((SELECT id FROM users WHERE userid = ?), ?, ?)", data.userid, data.userid, data.totalratio);
});
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(req.body);
});
var generateId = function() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var userid = '';
var length = 64;
for (var i = length; i > 0; i--) {
userid += chars[Math.round(Math.random() * (chars.length - 1))];
}
return userid;
}
/**
* Generate a userid for a new user, this will uniquely identify them in our database.
* If generation fails, userid will return null.
*/
dispatcher.onPost("/newuser", function(req, res) {
db.serialize(function() {
db.all("SELECT userid FROM users", function(err, rows) {
res.writeHead(200, {'Content-Type': 'application/json'});
var userid = generateId();
if (rows != null) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].userid == userid) {
res.end(JSON.stringify({"userid": null}));
return;
}
}
}
res.end(JSON.stringify({"userid": userid}));
});
});
});
/**
* Calculate and recieve the ratio of overall purchases of users
*
* totalratio - the ratio of purchases / household size
*/
dispatcher.onPost("/gimme/totalratio", function(req, res) {
db.serialize(function() {
db.all("SELECT totalratio FROM users", function(err, rows) {
var data = {
"totalratio": 0
}
for (var i = 0; i < rows.length; i++) {
data.totalratio += rows[i].totalratio;
}
data.totalratio = data.totalratio / rows.length;
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(data));
});
});
});
/**
* Accept user input and store it in database
*/
dispatcher.onPost("/update/totalratio", function(req, res) {
var data = JSON.parse(req.body);
db.serialize(function() {
db.all("INSERT OR REPLACE INTO users (id, userid, totalratio) VALUES ((SELECT id FROM users WHERE userid=?), ?, ?)", data.userid, data.userid, data.totalratio);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end("");
});
});
var server = http.createServer(handleRequest);
server.listen(PORT, function() {
console.log("server listening on: http://localhost:%s", PORT);
});