-
Notifications
You must be signed in to change notification settings - Fork 0
/
server2.js
245 lines (225 loc) · 7.64 KB
/
server2.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// SETUP required modules, settings and headers
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jsonfile = require('jsonfile');
const filePath = __dirname + "/" + "categories.json";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(function (req, res, next) {
"use strict";
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
next();
});
// WEB SERVICE ENDPOINTS (REST API services)
// hello
app.get('/hello', function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end("Hello World from Node.js Back-end");
});
// GET category/all
app.get('/category/all', function (req, res) {
jsonfile.readFile(filePath)
.then((obj) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify(obj));
console.log("Reading server side JSON file OK.\n" + JSON.stringify(obj));
})
.catch(() => {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.");
}
);
});
// GET category based on ID
app.get('/category', function (req, res) {
let id = req.query.id;
if (!id) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.\n" + "No ID supplied in query.");
} else if (isNaN(id)) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.\n" + "The supplied ID is not a number.");
} else {
fetchItemBasedOnId(res, id);
}
});
// POST category (id, name, budget)
app.post('/add_category', function (req, res) {
let id = req.body.id;
let name = req.body.name;
let budget = req.body.budget;
let newItem = { id, name, budget };
addItemToJsonArrayFile(res, newItem);
});
// DELETE category?id=1001
app.delete('/delete_category', function (req, res) {
let id = req.query.id;
if (!id) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.\n" + "No ID supplied in query.");
} else if (isNaN(id)) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.\n" + "The supplied ID is not a number.");
} else {
deleteItemBasedOnId(res, id);
}
});
// GET categories by budget limit
app.get('/category/idsByBudgetLimit', function (req, res) {
let limit = req.query.limit;
let above = req.query.above;
if (!limit || !above) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.\n" + "Incomplete parameters supplied in query.");
} else if (isNaN(limit)) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.\n" + "Limit is not a number.");
} else if (above !== "true" && above !== "false") {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.\n" + "Parameter in wrong format.");
} else {
fetchIdsByBudgetLimit(res, limit, above);
}
});
// HELPER FUNCTIONS
function fetchItemBasedOnId (res, id) {
let item = null;
jsonfile.readFile(filePath)
.then((obj) => {
for (let i = 0; i < obj.length; i++) {
if (obj[i].id === Number(id)) {
item = obj[i];
}
};
if (item) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify(item));
console.log("Reading server side JSON file OK.\n" + "Item found: " + JSON.stringify(item));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end();
console.log("Reading server side JSON file OK.\n" + "No item found with ID = " + id + ".");
};
})
.catch(() => {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.");
}
);
};
function deleteItemBasedOnId (res, id) {
let item = null;
jsonfile.readFile(filePath)
.then((obj) => {
for (let i = 0; i < obj.length; i++) {
if (obj[i].id === Number(id)) {
item = obj.splice(i, 1);
}
};
if (item) {
jsonfile.writeFile(filePath, obj)
.then(() => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end();
console.log("Writing JSON to server file system OK.\n" + "Item deleted: " + JSON.stringify(item));
})
.catch(() => {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end();
console.error("Writing JSON to server file system failed.");
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end();
console.log("Reading server side JSON file OK.\n" + "No item found with ID = " + id + ".");
};
})
.catch(() => {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.");
}
);
};
function addItemToJsonArrayFile (res, newItem) {
jsonfile.readFile(filePath)
.then((obj) => {
let isItemNew;
for (i in obj) {
if (obj[i].id == newItem.id) {
obj[i] = newItem;
isItemNew = false;
break;
} else {
isItemNew = true;
}
}
if (isItemNew) {
obj.push(newItem);
}
jsonfile.writeFile(filePath, obj)
.then(() => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end();
console.log("Writing JSON to server file system OK.\n" + "Item added: " + JSON.stringify(newItem));
})
.catch(() => {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end();
console.error("Writing JSON to server file system failed.");
});
})
.catch(() => {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.");
}
);
};
function fetchIdsByBudgetLimit(res, limit, above) {
let list = [];
jsonfile.readFile(filePath)
.then((obj) => {
for (let i = 0; i < obj.length; i++) {
if (above == "true") {
if (Number(obj[i].budget) > Number(limit)) {
list.push(obj[i].id);
}
} else if (above == "false") {
if (Number(obj[i].budget) <= Number(limit)) {
list.push(obj[i].id);
}
}
};
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify(list));
console.log("Reading server side JSON file OK.\n" + "List built: " + JSON.stringify(list));
})
.catch(() => {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end();
console.error("Reading server side JSON file failed.");
}
);
};
// START SERVER
var server = app.listen(3001, function () {
"use strict";
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});