viczam
9/25/2016 - 7:47 AM

hapi plugin conventions

hapi plugin conventions

  • sharing functionality between plugins
  • extending 3rd party plugins
// index.js - the main entry point
import Joi from 'joi';
import pkg from '../package.json';
import routes from './routes';
import pluginOptionsSchema from './schemas/pluginOptions';

export const register = (server, options, next) => {
  const { error, value } = Joi.validate(options, pluginOptionsSchema);
  if (error) {
    return next(error);
  }

  server.route(routes);

  return next();
};

register.attributes = {
  pkg,
  dependencies: ['someOtherPlugin'],
};
- src
- - lib
- - handlers
- - - handler1.js
- - - handler2.js # could be a pre as well
- - server-methods
- - routes
- - - index.js
- - - products.js
- - schemas
- - - pluginOptions.js
- - - product.js
- - index.js
- test
- .eslintignore
- .eslintrc
- .gitignore
- README.md
- package.json

Examples - https://github.com/viczam/hb-user

Routes

  • handlers should be located in the same place as the route configuration (validate, pre's etc)
    • you don't have to switch files to see what params / query / payload you expect
    • you can see all the route pre's you'll receive
  • config order:
    • path
    • method
    • handler
    • config
  • route handlers shouldn't be arrow functions if you plan to bind an object to the context (and you should)
  • keep your handlers skinny - they should only process the request and return (reply) a response
  • use request.log(tags, data) in your handlers

Rules

  • if your plugin accepts options, always create a Joi schema for them and do the validation in your register method.