hapi-bookshelf-serializer

6.0.0 • Public • Published

Hapi Bookshelf Serializer

npm version

This plugin takes Bookshelf.js models that are returned via Hapi's reply method and serializes them using a user-defined serialize method.

Registering the Plugin

const Hapi = require('@hapi/hapi');

const server = new Hapi.Server();

await server.register([
  require('hapi-bookshelf-serializer'),
]);

Defining Models

Models are defined just like all Bookshelf.js models, except for one small addition. A serialize function is added with the following signature function (request) { }. All model properties can be accessed in the serialize function via this.get() and the function will be passed the current Hapi request as request. The serialize function can either return a static value or a Promise.

Serializing Related Models

Currently there is no support in this module for automatically serializing all related models so you will need to call the function manually.

Example

// models/role.js
const bookshelf = require('bookshelf')(require('knex')(config));

module.exports = bookshelf.Model.extend({
  tableName: 'roles',
  serialize: function(request) {
    return {
      this.get('id'),
      this.get('name')
    };
  }
});

// models/user.js
const bookshelf = require('bookshelf')(require('knex')(config));
const Role      = require('./role.js');

module.exports = bookshelf.Model.extend({
  tableName: 'users',
  roles: this.belongsToMany(Role),
  serialize: function (request) {
    return {
      this.get('id'),
      this.get('email'),
      roles: this.related('roles').map(function (role) {
        return role.serialize(request);
      });
    };
  }
});

This plugin pairs well with the hapi-bookshelf-models plugin which makes registering models from a directory super easy.

Readme

Keywords

Package Sidebar

Install

npm i hapi-bookshelf-serializer

Weekly Downloads

173

Version

6.0.0

License

MIT

Unpacked Size

14.2 kB

Total Files

11

Last publish

Collaborators

  • tanya.sah
  • hunteryoakum
  • rdimouro7373
  • lobstertroy
  • joshnkoy
  • michel_lob
  • haroutrs
  • kjones_lob
  • eamon-barisone
  • nathanielwaldschmidtlob
  • zach.reed
  • richpodrazalob
  • kencrim
  • jorgelob
  • nick-place-lob
  • andrew.guterres
  • ajorczak
  • hanqingchen-lob
  • juan.frissdekereki
  • mmorgan-lob
  • karankwatra-lob
  • joey-bates-lob
  • luke.birdeau
  • mg-lob
  • vmangwani
  • sachinlob
  • kc-lob
  • nick.perri
  • siddharthpant92
  • bethqiang
  • kplob
  • samkitsheth95
  • erin-doyle
  • rich_seviora_lob
  • jfdavidson
  • meussdorffer
  • shannamurry
  • davidnutting-lob
  • amaan_lob
  • team.platform.lob.com
  • elijah-lob
  • jlowsley-lob
  • barnabygo
  • james.cho
  • douglaje
  • lob-owner
  • graeme.lowe.lob