-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
87 lines (79 loc) · 2.19 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
let maps = [
// temporary database that has some records already.
{
address: "Lahore, Pakistan",
id: "1",
coordinates: {
lat: "31.5203696",
lng: "74.35874729999999"
}
},
{
address: "Berlin, Germany",
id: "2",
coordinates: {
lat: "52.52000659999999",
lng: "13.404954"
}
}
];
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
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",
"PUT, POST, GET, DELETE, OPTIONS, PATCH"
);
next();
});
app.get("/", (req, res) => {
res.status(200).json("Wellcome to backend of geocodes-app-backend");
});
app.get("/list", (req, res) => {
res.status(200).json({ msg: "success", data: maps });
});
app.post("/add", (req, res) => {
const { data } = req.body;
if (data) {
maps.push(data);
return res.status(200).json({ msg: "success", data: maps });
}
return res.status(422).json("Malformed Request");
});
app.delete("/remove", (req, res) => {
const { data } = req.body;
if (data.id) {
const index = maps.findIndex(function(i) {
return i.id === data.id;
});
if (index > -1) {
maps.splice(index, 1);
return res.status(200).json({ msg: "success", data: maps });
}
return res.status(404).json({ msg: "does not exists" });
}
return res.status(422).json("Malformed Request");
});
app.patch("/update", (req, res) => {
const { id, newData } = req.body;
if (id && newData) {
const index = maps.findIndex(function(i) {
return i.id === id;
});
if (index > -1) {
maps[index] = newData;
return res.status(200).json({ msg: "success", data: maps });
}
return res.status(404).json({ msg: "does not exist" });
}
return res.status(422).json("Malformed Request");
});
app.listen(8000, () => console.log("Backend server is running!"));