-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_sql.js
409 lines (359 loc) · 10.9 KB
/
server_sql.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// load the express module
var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mysql = require('mysql');
var fs = require('fs');
var jf = require('jsonfile');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'bookhive'
});
// declare our app
var app = express();
// configuration and middleware, body parser is needed to parse POST into JSON
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
// this will serve as our resource on the server, implements JSON read/write file
var books = [];
var db =[];
var file = 'data.json';
db = JSON.parse(fs.readFileSync(file, 'utf8'));
if (typeof db[0] !== 'undefined')
for (var i=0; i<db.length; i++)
books.push(db[i]);
// collection endpoints
// get all books
app.get('/books', function(req, res){
res.jsonp(books);
});
// post new book to the collection
app.post('/books', function(req, res){
// req.body contains the incoming fields and values
var imgSrc = req.body.imgSrc;
var title = req.body.title;
var author = req.body.author;
var review = req.body.review;
var price = req.body.price;
var dateOfPub = req.body.dateOfPub;
var rating = req.body.rating;
var numOfSales = req.body.numOfSales;
var promotions = req.body.promotions;
var genre = req.body.genre;
var book = {imgSrc: imgSrc, title: title, author: author, review: review, price: price,
dateOfPub: dateOfPub, rating: rating, numOfSales: numOfSales, promotions: promotions, genre: genre };
books.push(book);
jf.writeFile(file, books, function(err) {
console.log(err)
});
res.jsonp({
msg: 'book created',
data: books[books.length-1]
});
});
// document endpoints
// get info about book by title
// for eg: /books/john-doe
app.get('/books/:title', function(req, res){
// get the title from the params
/* If we dont use arrays
var title = req.params.title;
res.jsonp(books[title]);
*/
var success = false;
var result = [];
var title = req.params.title;
for (var i=0; i<books.length; i+=1) {
if (books[i].title.indexOf(title) > -1) {
result.push(books[i]);
success = true;
}
}
if (success === true)
return res.jsonp(result);
res.status(500).send('No such book title!');
});
// Get the books in given price range with POST
app.post('/books/price', function(req, res){
// req.body contains the incoming fields and values
console.log(req.body);
var minPrice = req.body.minPrice;
var maxPrice = req.body.maxPrice;
var success = false;
var result = [];
for (var i=0; i<books.length; i+=1) {
if ((Number(books[i].price) >= Number(minPrice)) &&
(Number(books[i].price) <= Number(maxPrice))) {
result.push(books[i]);
success = true;
}
}
if (success === true)
res.jsonp({
msg: 'books found in price range!',
data: result
});
else
res.status(500).send('No such books in current price range!');
});
// get info about book by rating
// for eg: /books/john-doe
app.get('/books/rating/:rating', function(req, res){
// get the title from the params
/* If we dont use arrays
var title = req.params.title;
res.jsonp(books[title]);
*/
var success = false;
var result = [];
var rating = req.params.rating;
for (var i=0; i<books.length; i+=1) {
if (books[i].rating == rating) {
result.push(books[i]);
success = true;
}
}
if (success === true)
return res.jsonp(result);
res.status(500).send('No such books with this rating!');
});
//Lesson learned! '/authors/:author' DO matter!
// '/authors/' create a different search namespace so to say
// while ':author' searches for a field/key in the data and
// therefore should be a valid one
// document endpoints
// get info about book by author
// for eg: /books/stephen%20king
app.get('/authors/:author', function(req, res){
// get the title from the params
/* If we dont use arrays
var author = req.params.author;
res.jsonp(books[author]);
*/
var success = false;
var result = [];
var author = req.params.author;
for (var i=0; i<books.length; i+=1) {
if (books[i].author.indexOf(author) > -1) {
result.push(books[i]);
success = true;
}
}
if (success === true)
return res.jsonp(result);
res.status(500).send('No such book author!');
});
//Multiple keys (author AND genre) search
app.get('/books/:author/:genre', function(req, res){
// get the title from the params
/* If we dont use arrays
var author = req.params.author;
res.jsonp(books[author]);
*/
var success = false;
var result = [];
var author = req.params.author;
var genre = req.params.genre;
for (var i=0; i<books.length; i+=1) {
if (books[i].author.indexOf(author) > -1 && books[i].genre.indexOf(genre) > -1) {
result.push(books[i]);
success = true;
}
}
if (success === true)
return res.jsonp(result);
res.status(500).send('No such book author and genre!');
});
// get info about book by date of publishing
// for eg: /dates/2015-01
app.get('/dates/:dateOfPub', function(req, res){
// get the title from the params
/* If we dont use arrays
var dateOfPub = req.params.dateOfPub;
res.jsonp(books[dateOfPub]);
*/
var success = false;
var result = [];
var dateOfPub = req.params.dateOfPub;
for (var i=0; i<books.length; i+=1) {
if (books[i].dateOfPub.indexOf(dateOfPub) > -1) {
result.push(books[i]);
success = true;
}
}
if (success === true)
return res.jsonp(result);
res.status(500).send('No such book published at the given date! Mind the MMM-YYYY format!');
});
// put an updated version of a book by title
app.put('/books/:title', function(req, res){
// get the title from the params
var title = req.params.title;
var counter=0;
// update the info from the body if passed or use the existing one
/* If not using array
books[title].author = req.body.author;
*/
for (var i=0; i<books.length; i+=1) {
if (books[i].title == title) {
books[i].imgSrc = req.body.imgSrc;
books[i].author = req.body.author;
books[i].review = req.body.review;
books[i].price = req.body.price;
books[i].dateOfPub = req.body.dateOfPub;
books[i].rating = req.body.rating;
books[i].numOfSales = req.body.numOfSales;
books[i].promotions = req.body.promotions;
books[i].genre = req.body.genre;
counter=i;
}
}
jf.writeFile(file, books, function(err) {
console.log(err)
});
res.jsonp({
msg: 'Book data updated',
data: books[counter]
});
});
// delete an existing book by title
app.delete('/books/:title', function(req, res){
var title = req.params.title;
var status = 'failed';
/* if(books[title]){
delete(books[title])
res.jsonp(title + ' successfully deleted!');
} else {
res.jsonp(title + ' does not exist!');
}*/
for (var i=0; i<books.length; i+=1) {
if (books[i].title == title) {
books.splice(i, 1);
status = i;
}
}
if (status !== 'failed'){
jf.writeFile(file, books, function(err) {
console.log(err)
});
res.jsonp(title + ' successfully deleted!');
}
else
res.jsonp(title + ' does not exist!');
});
//Bookstores calls
//Get all stores
app.get('/stores', function(req, res){
connection.query("SELECT * FROM stores", function(error, rows, fields){
if(rows.length > 0){
//var row = rows[0];
res.jsonp(rows);
// res.write(JSON.stringify(row));
// res.end("");
}
else{
res.end("There are no bookstores.");
}
});
});
// post new store to the collection
app.post('/stores', function(req, res){
// req.body contains the incoming fields and values
var name = req.body.name;
var city = req.body.city;
var info = req.body.info;
var phone = req.body.phone;
var workingTime = req.body.workingTime;
var booksInStore = req.body.booksInStore.join(';');
var latitude = Number(req.body.latitude);
var longitude = Number(req.body.longitude);
connection.query("INSERT INTO stores(name, city, info, phone, workingTime, booksInStore, latitude, longitude) VALUES('"
+ name + "', '" + city + "', '" + info+ "', '" + phone+ "', '" + workingTime+ "', '" + booksInStore+ "', '" + latitude
+ "', '" + longitude+"');", function(error, rows, fields){
res.end("SQL INSERT bookstore completed.");
});
var store = {name: name, city: city, info: info, phone: phone, workingTime: workingTime,
booksInStore: booksInStore, latitude: latitude, longitude: longitude};
res.jsonp({
msg: 'bookstore created',
data: store
});
});
// put an updated version of a store by name
app.put('/stores/:name', function(req, res){
// get the name from the params
var name = req.params.name;
city = req.body.city;
info = req.body.info;
phone = req.body.phone;
workingTime = req.body.workingTime;
booksInStore = req.body.booksInStore.join(';');
latitude = Number(req.body.latitude);
longitude = Number(req.body.longitude);
// update the info from the body if passed or use the existing one
connection.query("UPDATE stores SET name = '" + name+"', city = '" + city+"',info = '"+info+"',workingTime ='"+workingTime+
"',booksInStore='"+booksInStore+"',latitude='"+latitude+"',longitude = '"+longitude+
"' WHERE name = '" + name+"';", function(error, rows, fields){
if(rows>0){
res.jsonp({
msg: 'Store data updated, SQL query completed.',
data: bookstores[counter]
});
}
else
console.log("No bookstores with name = "+name+" found.");
});
});
// delete an existing store by name
app.delete('/stores/:name', function(req, res){
var name = req.params.name;
connection.query("DELETE FROM stores WHERE name = '" + name +"';", function(error, rows, fields){
if (rows>0)
res.jsonp(name + ' successfully deleted!');
else
res.jsonp(name + ' does not exist!');
});
});
//Get all stores that contain a book by title
app.get('/stores/books/:booksInStore', function(req, res){
// get the title from the params
var booksInStore = req.params.booksInStore;
connection.query("SELECT * FROM stores WHERE booksInStore LIKE '%"+booksInStore+"%';", function(error, rows, fields){
if(rows.length > 0){
//var row = rows[0];
res.jsonp(rows);
// res.write(JSON.stringify(row));
// res.end("");
}
else{
//res.end("No such book in any of the stores!");
res.status(500).send('No such book in any of the stores!');
}
});
});
//Get all stores that are located in a given city
app.get('/stores/:city', function(req, res){
// get the title from the params
var city = req.params.city;
connection.query("SELECT * FROM stores WHERE city = '"+city+"';", function(error, rows, fields){
if(rows.length > 0){
//var row = rows[0];
res.jsonp(rows);
// res.write(JSON.stringify(row));
// res.end("");
}
else{
//res.end("No such book in any of the stores!");
res.status(500).send('No such store in the given city!');
}
});
});
var server = app.listen(1337, function() {
console.log('Listening on port %d', server.address().port);
});