Jonathan Eustace
Jonathan Eustace

Reputation: 2489

Logging in HapiJS v16 Models

I've created a HapiJS project, using my own MVC pattern.

When I want to log from inside my controllers in some cases. Currently when I want to log from my controllers I simply invoke request.log. I'm using Good as a logging plugin.

For example:

const user = function(req, res){
   // do stuff
   req.log(['info'], 'some log info here');
};

module.exports = {
   user,
};

How can I log from inside my models where I have no request object? I don't want to have to pass in my request object into the methods of the model.

Upvotes: 0

Views: 129

Answers (1)

Ernest Jones
Ernest Jones

Reputation: 584

If you plan to register models as plug in, you will have access to the server object and so, you will be able to use server.methods

EDIT

In my company we declare routes as plug in (see code below)

exports.register = function (server, options, next) {
  server.route({
    method: 'POST',
    path: '/FOO/BAR'

    handler(request, reply) {}
    });

    return next();
};

exports.register.attributes = {
    name: 'routes-foobar'
};

And we register as such :

server.register([
  require('./route-foo-bar'),
  ...,
]);

This way we have the server objects in our route What I would do in your case is register my models as server methods and use them in my routes.

The same goes for logging.

I would register my log function as a server method and call them from inside my models

I don't know if it's the good way to do that but that's a least a working one

Upvotes: 1

Related Questions