Skip to content

Instantly share code, notes, and snippets.

@samrocksc
Forked from nvcexploder/hapiExample.js
Last active August 28, 2015 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samrocksc/01929eaf22d3253705ec to your computer and use it in GitHub Desktop.
Save samrocksc/01929eaf22d3253705ec to your computer and use it in GitHub Desktop.
basic hapi.js example highlighting HTTP methods and a few request parameters
/*
For this to run, ensure that `npm install hapi` has happened in your directory
setup whilst writing this:
iojs v. 1.0.5
hapi 8.2.0
*/
var Hapi = require('hapi');
var server = new Hapi.Server();
var connection = server.connection({
port: 8080,
host: 'localhost'
});
var internals = {
rooms: {}
};
var handlers = {
post: function (request, reply) {
//curl http://localhost:8080/rooms -X POST -H 'Content-Type: application/json' -d '{"name":"rainbow dash"}'
console.log('In the rooms.post handler with this: '
+ JSON.stringify(request.payload));
var room = {
name: request.payload.name,
id: Math.floor(Math.random() * 10000)
};
internals.rooms[room.id] = room;
/*
'created' sets the reply's response to 201 and
sets the http location header to the URL you specify
*/
reply(room).created('http://localhost/room/'+room.id);
},
getAll: function (request, reply) {
//curl http://localhost:8080/rooms
console.log('In the rooms.get handler');
reply(internals.rooms);
},
getOne: function (request, reply) {
//curl http://localhost:8080/room/5215
console.log('In the room.get function with this: '
+ JSON.stringify(request.params));
reply(internals.rooms[request.params.id]);
},
put: function (request, reply) {
//curl -X PUT http://localhost:8080/room/5215 -H 'Content-Type: application/json' -d '{"name": "rainbow dash"}'
console.log('In the room.put function with this: '
+ JSON.stringify(request.params) + ' and this '
+ JSON.stringify(request.payload));
var room = internals.rooms[request.params.id];
room.name = request.payload.name;
internals.rooms[room.id]=room;
reply(room);
},
remove: function (request, reply) {
//curl -X DELETE http://localhost:8080/room/5215
console.log('In the room.put function with this: '
+ JSON.stringify(request.params));
delete internals.rooms[request.params.id];
reply({ accepted: true, rooms: internals.rooms });
}
};
server.route([
{ path: '/rooms', method: 'POST', handler: handlers.post },
{ path: '/rooms', method: 'GET', handler: handlers.getAll },
{ path: '/room/{id}', method: 'GET', handler: handlers.getOne },
{ path: '/room/{id}', method: 'PUT', handler: handlers.put },
{ path: '/room/{id}', method: 'DELETE', handler: handlers.remove }
]);
server.start(function () {
console.log('server ready on port 8080');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment