Overview

This Bookshelf.js plugin enables you to define masks on your models and serialize to JSON based on its fields using the json-mask API.

Status

npm version node version build status coverage status

Installation

Install the package via npm:

$ npm install --save bookshelf-mask

Usage

Require and register the bookshelf-mask plugin:

var bookshelf = require('bookshelf')(knex);
var mask = require('bookshelf-mask');

bookshelf.plugin(mask);

Define masks on your models with masks class property:

var Author = bookshelf.Model.extend({
  posts: {
    return this.hasMany(Post);
  },
  tableName: 'Author'
}, {
  masks: {
    custom: 'id,name'
  }
});

If you're using ES6 class syntax, define masks as static property:

class Author extends bookshelf.Model {
  get tableName() {
    return 'Author';
  }

  posts() {
    return this.hasMany(Post);
  }

  static masks = {
    custom: 'id,name'
  }
}

Use the mask method to serialize the registered masks or pass the fields directly:

Author
  .forge({ name: 'foo' })
  .fetch({ withRelated: 'posts' })
  .then(function(model) {
    console.log(model.mask('custom'));
    // => { id: 1, name: 'foo' }
    console.log(model.mask('name,posts(title,body)'));
    // => { name: 'foo', posts: [{ title: 'biz', body: 'baz' }, { title: 'qux', body: 'qix' }]}
  });

The mask method can be applied to collections and the same options accepted in toJSON can also be provided.

Contributing

Contributions are welcome and greatly appreciated, so feel free to fork this repository and submit pull requests.

Setting up

$ npm test

Linting

bookshelf-mask enforces linting using ESLint with the Seegno-flavored ESLint config. We recommend you to install an eslint plugin in your editor of choice, although you can run the linter anytime with:

$ eslint src test

Pull Request

Please follow these advices to simplify the pull request workflow:

License

MIT