forked from hapijs/hapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
executable file
·65 lines (47 loc) · 1.41 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
var Hapi = require('../lib');
var Joi = require('joi');
var routes = [
{ method: 'GET', path: '/products', config: { handler: getProducts, validate: { query: { name: Joi.string() } } } },
{ method: 'GET', path: '/products/{id}', config: { handler: getProduct } },
{ method: 'POST', path: '/products', config: { handler: addProduct, validate: { payload: { name: Joi.string().required().min(3) } } } }
];
var server = new Hapi.Server(8000);
server.route(routes);
server.start(function () {
console.log('Server started at: ' + server.info.uri);
});
var products = [
{
id: 1,
name: 'Guitar'
},
{
id: 2,
name: 'Banjo'
}
];
function getProducts(request, reply) {
if (request.query.name) {
return reply(findProducts(request.query.name));
}
reply(products);
}
function findProducts(name) {
return products.filter(function (product) {
return product.name.toLowerCase() === name.toLowerCase();
});
}
function getProduct(request, reply) {
var product = products.filter(function (p) {
return p.id === parseInt(request.params.id);
}).pop();
reply(product);
}
function addProduct(request, reply) {
var product = {
id: products[products.length - 1].id + 1,
name: request.payload.name
};
products.push(product);
reply(product).code(201).header('Location', '/products/' + product.id);
}