-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
109 lines (95 loc) · 1.98 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
'use strict';
const Hapi = require('hapi');
const Path = require('path');
const server = new Hapi.Server();
server.connection({ port: 3001, routes: { cors: true } });
let posts = [
{
id: 1,
title: 'Post 1',
body: 'This is Post n.1'
},
{
id: 2,
title: 'Post 2',
body: 'This is Post n.2'
}
];
var generateNextId = function(generateNextId) {
let ids = posts.map((p) => {
return p.id;
});
return Math.max.apply(Math, ids) + 1;
};
server.route({
method: 'GET',
path: '/api/posts',
handler: function (req, reply) {
return reply(JSON.stringify(posts));
}
});
server.route({
method: 'GET',
path: '/api/posts/{id}',
handler: function (req, reply) {
let post = posts.filter((p) => {
return p.id == req.params.id;
})[0];
if (post) {
return reply(JSON.stringify(post));
}
return reply('Post not found').code(404);
}
});
server.route({
method: 'POST',
path: '/api/posts',
handler: function (req, reply) {
var newPost = {
id: generateNextId(),
title: req.payload.title,
body: req.payload.body
};
posts.push(newPost);
return reply(newPost);
}
});
server.route({
method: 'DELETE',
path: '/api/posts/{id}',
handler: function (req, reply) {
let pLength = posts.length;
posts = posts.filter((p) => {
return p.id != req.params.id;
});
if (pLength == posts.length) {
return reply('Post not found').code(404);
}
return reply(true);
}
});
server.route({
method: 'PUT',
path: '/api/posts/{id}',
handler: function (req, reply) {
let modified;
posts.map((p) => {
if (p.id == req.params.id) {
p.title = req.payload.title;
p.body = req.payload.body;
modified = p;
}
return p;
});
if (modified) {
return reply(modified);
}
return reply('Post not found').code(404);
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});