poeticninja / hapi-ninja

Boilerplate Hapi server example. Node.js, Hapi, and Swig.
MIT License
378 stars 56 forks source link

Plugin availability in controllers. #9

Closed devinivy closed 10 years ago

devinivy commented 10 years ago

Is it impossible to reference a Hapi plugin in a controller's handler? If so, that seems like an issue. Is there any way around this?

devinivy commented 10 years ago

Sorry, this issue was due to some ignorance on my part! I've figured it out. For those trying to figure this out, the plugins live within the request parameter of the handler: req.server.plugins.

marcus7777 commented 9 years ago

It would be really cool to have some clear documentation on where to put plugins i'm still trying to work it out. although this is my first dive into node, and i wonder if it's going to take me longer than a week to work it out?

devinivy commented 9 years ago

@marcus7777, see here: https://github.com/poeticninja/hapi-ninja/blob/master/server/config/plugins.js

marcus7777 commented 9 years ago

@devinivy Thanks joi plugin if I was to add the joi plugin I run npm install joi and add to the
server.pack.register([ { plugin: require("joi") }, ...

right?

big thank you to @poeticninja

Marcus

devinivy commented 9 years ago

Actually, Joi is an npm package that hapi uses, but it's not a hapi plugin. That is, certain places where validation take place, hapi will accept a Joi validation object. But you don't need to register it as a hapi plugin. Hapi includes a version of Joi that it uses for certain tasks. You can use Joi standalone. See the Joi docs: https://github.com/hapijs/joi

poeticninja commented 9 years ago

@marcus7777 your welcome.

Also @devinivy is right. If you want to use joi for validation then you just need to use it in the route validation. There is not need to have hapi initiate the plugin directly. Just require it and use.

Here is a simple example of using Joi with Hapi.


var joi = require('joi');

server.route({
  method: 'POST',
  path: '/user',
  config: {
    validate: {
      payload: {
        dob: joi.date(),
        active: joi.boolean().default(true)
      }
    },
    handler: function (request, reply) {
      reply('You passed in the right payload!');
    }
  }
});

Now there will be validation on the payload object that gets passed into the route. The dob property has to be a date and the active property has to be true or false and if nothing is passed into the active property it will provide a default of true.

:)