Skip to content

Instantly share code, notes, and snippets.

@mtharrison
Last active June 10, 2016 07:34
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 mtharrison/633ee77d1ea0e2a2653403ce85c78f2a to your computer and use it in GitHub Desktop.
Save mtharrison/633ee77d1ea0e2a2653403ce85c78f2a to your computer and use it in GitHub Desktop.
'use strict';
// The whole app is a hapi plugin
module.exports = function (server, options, next) {
server.route({
method: 'GET',
path: '/add/{a}/{b}',
handler: function (request, reply) {
const { a, b } = request.params;
server.methods.sum(a, b, (err, res) => { // this method doesn't exist until plugins are registered
if (err) {
return reply(err);
}
return reply(res);
});
}
});
server.register(require('./plugin'), next);
};
module.exports.attributes = { name: 'app', version: '1.0.0' };
'use strict';
// An example of a plugin that takes some time to initialize
module.exports = function (server, option, next) {
setTimeout(() => {
const add = (a, b, next2) => next2(null, Number(a) + Number(b));
server.method('sum', add);
return next();
}, 1000);
};
module.exports.attributes = { name: 'plugin', version: '1.0.0' };
'use strict';
const Code = require('code');
const Hapi = require('hapi');
const Lab = require('lab');
const expect = Code.expect;
const lab = exports.lab = Lab.script();
const it = lab.it;
const App = require('.');
const getServer = function (onCleanup, next) {
const server = new Hapi.Server();
server.connection();
onCleanup((callback) => {
server.stop(callback);
});
server.register(App, (err) => {
expect(err).to.not.exist();
server.initialize((err) => {
expect(err).to.not.exist();
return next(server);
});
});
};
it('can add 1 + 5', (done, onCleanup) => {
getServer(onCleanup, (server) => {
server.inject('/add/1/5', (res) => {
expect(res.statusCode).to.equal(200);
expect(res.result).to.equal(6);
done();
});
});
});
it('can add 7 + 8', (done, onCleanup) => {
getServer(onCleanup, (server) => {
server.inject('/add/7/8', (res) => {
expect(res.statusCode).to.equal(200);
expect(res.result).to.equal(15);
done();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment