forked from geek/hapi-example
/
routes.js
81 lines (63 loc) · 1.53 KB
/
routes.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
'use strict';
const Joi = require('joi');
let internals = {};
internals.getProducts = function (request, reply) {
if (request.query.name) {
return reply(internals.findProducts(request.query.name));
}
reply(internals.products);
}
internals.findProducts = function (name) {
return internals.products.filter((product) => {
return product.name.toLowerCase() === name.toLowerCase();
});
}
internals.getProduct = function (request, reply) {
const filtered = internals.products.filter((product) => {
return product.id === parseInt(request.params.id);
}).pop();
reply(filtered);
}
internals.addProduct = function (request, reply) {
const product = {
id: internals.products[internals.products.length - 1].id + 1,
name: request.payload.name
};
internals.products.push(product);
reply(product).created('/products/' + product.id);
}
module.exports = [{
method: 'GET',
path: '/products',
config: {
validate: {
query: {
name: Joi.string()
}
},
handler: internals.getProducts
}
}, {
method: 'GET',
path: '/products/{id}',
handler: internals.getProduct
}, {
method: 'POST',
path: '/products',
config: {
validate: {
payload: { name: Joi.string().required().min(3) }
},
handler: internals.addProduct
}
}];
internals.products = [
{
id: 1,
name: 'Guitar'
},
{
id: 2,
name: 'Banjo'
}
];