Sunday, 16 April 2017

How do I group route handlers in hapi.js

In my hapi.js application, I created a plugin for a collection of routes. The plugin contains in index file to define the routes, and a controller file to define the handlers. The following code is the starting point for the application.

index.js

exports.register = function (server, options, next) {
  server.route({
    method: 'GET',
    path: '/coins',
    handler: require('./getCoins')
  });

  next();
};

getCoins.js

module.exports = function (request, reply) {
  reply('get all coins called');
};

This works as expected. The problem arrises when I try to combine multiple handlers into one file. The offending code from the two files (index.js, controller.js) is as follows:

index.js

var controller = require('./controller.js');

exports.register = function (server, options, next) {
  server.route({
    method: 'GET',
    path: '/coins',
    handler: controller.getAllCoins()
  });

  server.route({
    method: 'POST',
    path: '/coins',
    handler: controller.createCoin()
  });

  next();
};

controller.js

var exports = module.exports = {};

exports.getAllCoins = function (request, reply) {
  reply('get all coins called');
};

exports.createCoin = function(request, reply) {
  reply('create new coin called');
};

When structuring my code in this manner, I end up with ERROR: reply is not a function. It seems that the reply object is not instantiated at all. I can define each handler in a separate file and that would work, but I'd prefer to keep the handlers in the same file if I can. What am I missing here?



via ThomasNichols89

No comments:

Post a Comment