-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
99 lines (92 loc) · 2.3 KB
/
index.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
const restify = require("restify");
const corsMw = require("restify-cors-middleware");
// Create the server
const server = restify.createServer({
name: "carl-persistence-server"
});
// Mock DB Setup
let NEXT_ID = 0;
const getNextId = () => `${++NEXT_ID}`;
const db = {
champions: [
{
id: getNextId(),
name: "Alistar",
roles: ["Support", "Fighter"]
}
]
};
const cors = corsMw({})
server.pre(cors.preflight)
server.use(cors.actual)
server.use(restify.plugins.bodyParser());
server.use(restify.plugins.queryParser());
// Example with query params
server.get("/champion", (req, res, next) => {
let champs = [];
if (req.query.name) {
champs = db.champions.filter(el => el.name.match(req.query.name));
} else {
// TODO: deep copy
champs = db.champions.map(el => Object.assign({}, el));
}
// TODO: not going to worry about error handling for this tutorial.
res.send(200, champs);
next();
});
// Standard rest verbs
server.post("/champion", (req, res, next) => {
let id
if (req.body) {
id = getNextId();
db.champions.push({
id: id,
name: req.body.name,
roles: req.body.roles
});
}
res.send(200, db.champions[db.champions.length - 1]);
next();
});
// Example with route params
server.get("/champion/:id", (req, res, next) => {
let champ = {};
if (req.params && req.params.id) {
let index = db.champions.findIndex(el => el.id === req.params.id);
if (index !== -1) {
champ = db.champions[index];
}
}
res.send(200, champ);
next();
});
server.put("/champion/:id", (req, res, next) => {
if (req.params && req.params.id && req.body) {
let index = db.champions.findIndex(el => el.id === req.params.id);
if (index !== -1) {
db.champions.splice(index, 1, {
name: req.body.name,
roles: req.body.roles
});
}
}
res.send(200);
next();
});
server.del("/champion/:id", (req, res, next) => {
if (req.params && req.params.id) {
let index = db.champions.findIndex(el => el.id === req.params.id);
if (index !== -1) {
db.champions.splice(index, 1);
}
}
res.send(200);
next();
});
server.on("error", function(err) {
console.error("Server error: ", err);
});
const port = 9005;
server.listen(port, function() {
console.log(`App listening at http://localhost:${port}`);
});