Implement REST calls

This commit is contained in:
hodasemi 2018-12-21 09:25:32 +01:00
parent 3352938c3e
commit db7b0175cc

View file

@ -43,7 +43,7 @@ app.get("/items", function (req, res) {
app.get("/items/:id", function (req, res) {
var requested_id = parseInt(req.params.id);
var answer = [];
var answer = ["No such id " + requested_id + " in database"];
for (var i = 0; i < json.length; i++) {
if (json[i].id == requested_id) {
@ -57,16 +57,16 @@ app.get("/items/:id", function (req, res) {
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 = [];
var answer = ["Range not possible"];
// 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++) {
for (var i; i < json.length; i++) {
// enable push when the first id is found
if (parseInt(json[i]["id"]) == first_requested_id) {
if (parseInt(json[i].id) == first_requested_id) {
enable_push = true;
}
@ -75,8 +75,8 @@ app.get("/items/:id1/:id2", function (req, res) {
answer.push(json[i]);
}
// leave when second id is found
if (parseInt(json[i]["id"]) == second_requested_id) {
// break when second id is found
if (parseInt(json[i].id) == second_requested_id) {
break;
}
}
@ -97,7 +97,7 @@ app.get("/properties", function (req, res) {
app.get("/properties/:num", function (req, res) {
let num = parseInt(req.params.num);
var answer = [];
var answer = ["No such property available"];
var i = 0;
@ -115,18 +115,40 @@ app.get("/properties/:num", function (req, res) {
// ----------------------------- POST ------------------------------
app.post("/items", function (req, res) {
var answer = bla();
res.send(answer);
var new_entry = req.body;
// set id
var last_id = parseInt(json[json.length - 1].id);
new_entry["id"] = (last_id + 1).toString();
// add entry to json
json.push(new_entry);
res.send("Added country " + new_entry.name + " to list!");
});
// ---------------------------- DELETE -----------------------------
app.delete("/items", function (req, res) {
var answer = bla();
res.send(answer);
var name = json[json.length - 1].name;
json.splice(-1, 1);
res.send("Deleted last country " + name + "!");
});
app.delete("/items/id", function (req, res) {
var answer = bla();
var requested_id = parseInt(req.params.id);
var answer = ["No such id " + requested_id + "in database"];
for (var i = 0; i < json.length; i++) {
if (json[i].id == requested_id) {
json.splice(i, 1);
answer = ["Item " + requested_id + " deleted successfully."];
break;
}
}
res.send(answer);
});