bookshelf-entity
Bookshelf plugin for controlling and formatting model serialization/output using json-entity. This plugin adds present
/render
(synonymous) methods to models and collections, both of which require an Entity to serialize the model. Since Entities only allow property whitelisting, you have very clear and detailed control over exactly which properties are exposed from your models. These methods also attempt to load any missing relations on your models to keep your model representations aligned. Entities also have a wealth of other formatting/modification options so you can make sure your API responses are perfect every time.
Installation
npm install bookshelf-entity --save
Usage
Apply the plugin:
const entity = require('bookshelf-entity');
bookshelf.plugin(entity);
Define an Entity:
const UserEntity = bookshelf.Entity.extend({
id: true,
firstName: true,
lastName: true,
fullName(user) {
return `${user.firstName} ${user.lastName}`;
},
location: { as: 'hometown', if: (user, options) => options.includeLocation },
address: { using: AddressEntity },
});
Specify Entity when calling present
or render
:
const User = Bookshelf.Model.extend({
tableName: 'users',
address() {
return this.hasOne(Address);
},
});
const user = User.forge({
id: 1,
firstName: 'Josh',
lastName: 'Swan',
location: 'San Francisco, CA',
});
user.present({ entity: UserEntity }).then((obj) => {
});
user.render({ entity: UserEntity }, { includeLocation: true }).then((obj) => {
});
Optional: You can also specify a defaultEntity
on your model as a fallback when present
/render
is invoked without specifying an Entity:
const User = bookshelf.Model.extend({
defaultEntity: UserEntity,
});
For a quick synchronous representation, you can also call the represent
method directly (it is called by present
/render
after loading any missing relations):
const user = User.forge({
id: 1,
firstName: 'Josh',
lastName: 'Swan',
location: 'San Francisco, CA',
});
user.represent(UserEntity, options);
See json-entity for all available options