Impl GET calls

This commit is contained in:
hodasemi 2018-12-20 20:45:48 +01:00
parent f62160fe4d
commit 3352938c3e

View file

@ -22,26 +22,113 @@ app.use(express.static(path.join(__dirname, "public")));
const csv = require('csvtojson')
var json;
csv()
.fromFile("world_data.csv")
.then((jsonObj) => {
json = jsonObj;
console.log(jsonObj);
/**
* [
* {a:"1", b:"2", c:"3"},
* {a:"4", b:"5". c:"6"}
* ]
*/
})
// Async / await usage
//const jsonArray = await csv().fromFile(csvFilePath);
/**************************************************************************
********************** handle HTTP METHODS ***********************
**************************************************************************/
// ------------------------------ GET ------------------------------
app.get("/items", function (req, res) {
console.log(json);
res.send(json);
});
app.get("/items/:id", function (req, res) {
var requested_id = parseInt(req.params.id);
var answer = [];
for (var i = 0; i < json.length; i++) {
if (json[i].id == requested_id) {
answer = [json[i]];
}
}
res.send(answer);
});
app.get("/items/:id1/:id2", function (req, res) {
var first_requested_id = parseInt(req.params.id1);
var second_requested_id = parseInt(req.params.id2);
var answer = [];
// check that first id is bigger than 0
// and the second one is the bigger one
if (first_requested_id >= 0 && second_requested_id > first_requested_id) {
var enable_push = false;
for (i; i < json.length; i++) {
// enable push when the first id is found
if (parseInt(json[i]["id"]) == first_requested_id) {
enable_push = true;
}
// push key when enabled
if (enable_push) {
answer.push(json[i]);
}
// leave when second id is found
if (parseInt(json[i]["id"]) == second_requested_id) {
break;
}
}
}
res.send(answer);
});
app.get("/properties", function (req, res) {
var answer = [];
for (var key in json[0]) {
answer.push(key);
}
res.send(answer);
});
app.get("/properties/:num", function (req, res) {
let num = parseInt(req.params.num);
var answer = [];
var i = 0;
for (var key in json[0]) {
if (i == num) {
answer = [key];
break;
}
i++;
}
res.send(answer);
})
// ----------------------------- POST ------------------------------
app.post("/items", function (req, res) {
var answer = bla();
res.send(answer);
});
// ---------------------------- DELETE -----------------------------
app.delete("/items", function (req, res) {
var answer = bla();
res.send(answer);
});
app.delete("/items/id", function (req, res) {
var answer = bla();
res.send(answer);
});
// DO NOT CHANGE!
// bind server to port