An elegance way to restrict API outputs for any web frameworks.
Baiji Entity gives you a simple schema for declaring JSON structures thats beats manipulating giant javascript object structures. This is particularly helpful when the generation process is fraught with conditionals and loops.
npm install baiji-entity
# or
yarn add baiji-entity
const Entity = require('baiji-entity');
// Presume we have a article object that needs to parse
let article = {
id: 1,
content: 'article content ...',
likesCount: 42,
wordsCount: 12422,
favoritesCount: 23,
commentsCount: 578,
visitors: 15,
createdAt: 1530003456793,
updatedAt: 1530008548865,
author: {
id: 789,
name: 'Felix',
email: '[email protected]',
articlesCount: 65,
password: 'xxxxxxx'
},
comments: [
{
content: 'Hello everyone!',
createdAt: '2018-03-29T20:45:28-08:00'
},
{
content: 'To you my good sir!',
createdAt: '2018-04-16T20:23:24-08:00'
}
]
}
// Define an article entity
let articleEntity = new Entity({
id: Number,
content: String,
visitors: Number,
createdAt: Date,
updatedAt: Date,
author: {
name: String,
email: String,
},
comments: [{
content: String,
createdAt: Date
}]
});
// Parse article data
articleEntity.parse(article);
// Outputs =>
{ id: 1,
content: 'article content ...',
visitors: 15,
createdAt: '2018-06-26T08:57:36.793Z',
updatedAt: '2018-06-26T10:22:28.865Z',
author: {
name: 'Felix',
email: '[email protected]'
},
comments: [
{
content: 'Hello everyone!',
createdAt: '2018-03-30T04:45:28.000Z'
},
{
content: 'To you my good sir!',
createdAt: '2018-04-17T04:23:24.000Z'
}
]
}
// See, only those fields specified will be exposed and formatted as we expect
Entity provide two global options that will help to simplify the entity definition.
Set default value to different types. Defaults are undefined
for all kinds of types.
NOTE: Only date
type has format
property, all types have default
property.
And format
property have two limit options: iso
and timestamp
.
Example:
Entity.types = {
string: { default: '' },
number: { default: 0 },
boolean: { default: false },
date: { format: 'iso', default: '' },
object: { default: {} }
};
Set default config to alter one key's name to another.
Example:
Entity.renames = { _id: 'id' };
const entity = new Entity({
_id: String
});
console.log(entity.parse({}));
// output => { id: '' }
Same effect as:
const entity = new Entity({
_id: { type: 'string', as: 'id', default: '' }
});
console.log(entity.parse({}));
// output => { id: '' }
const Entity = require('baiji-entity');
const entity = new Entity({
name: { type: 'string' },
sex: { type: 'number', as: 'gender' },
age: { type: 'number', default: 18 },
isAdult: {
type: 'boolean',
get(obj) {
return obj.age >= 18 ? true : false;
}
},
girlfriend: {
type: 'boolean',
default: true,
if: function(obj) {
return obj.age >= 16 ? true : false;
}
},
social: {
type: 'object',
using: SomeEntity,
get(obj, options) {
return {};
}
}
});
You can use the simpler syntax to define an entity. Attention please set Global config at project initialization.
const Entity = require('baiji-entity');
const entity = new Entity({
// like: { type: 'string', as: 'id', default: '' }
_id: String,
// like: { type: 'string', default: '' }
name: String,
// like: { type: 'number', default: 0 }
age: Number,
// like: { type: 'date', format: 'iso', default: '' }
birthday: Date
});
// Or you can have a different default value
const entity = new Entity({
// like: { type: 'string', default: 'baiji' }
name: 'baiji',
// like: { type: 'number', default: 10 }
age: 10,
});
Check if an entity object is instance of Entity object
Entity.isEntity(entity);
Clone provided Entity object
Entity.clone(entity);
An alias for .clone method
Entity.copy(entity);
Extend a new Entity object based on provided one and object
Entity.extend(entity, { name: true });
For Entity instance this always return true
entity.isEntity(entity);
Pick specific fields from current entity, return a new entity
const entity = new Entity({
id: String,
name: String,
age: Number,
children: [{
id: String,
sex: Number
}]
});
const pickedEntity = entity.pick('id name children{ id }');
/**
* => entity
* {
* id: String,
* name: String,
* children: [{ id: String }]
* }
*/
Add fields with corresponding value or function for final exposure, method could be chained
Options:
- as: rename the field to exposure
- value: set specific value for field
- default: set default value for undefined field
- type: normalize field value according to type option, case ignored, see more at https://github.com/baijijs/normalizer
- format: only applied for valid Date value, which automatically turn type option to
string
, now support format ofiso
andtimestamp
, case ignored - if: set a filter to determine if the field should be return, accept an object and return boolean
- using: use another Entity instance as the filed value
- get: function, for further manipulation of inputed object according to options
fn optional, for further manipulation of inputed object according to options
let entity = new Entity();
entity.add('name', { type: 'string' });
entity.add('name', { type: 'string', as: 'fullname' });
entity.add('sex', { type: 'number', value: 'male' });
entity.add('isAdult', { type: 'boolean' }, function(obj) { return obj && obj.age >= 18; });
entity.add('isAdult', { type: 'boolean', get(obj) { return obj && obj.age >= 18; } });
entity.add('activities', { using: myActivityEntity });
entity.add('extraInfo', { using: myExtraInfoEntity });
entity.add('condition', { if: function(obj, options) { return true } });
Same as .add function, return a new entity instead of modifying itself
An alias method for .add
An alias method for .safeAdd
Unexpose certain field, used for extended entity
Parse an input object according to Entity exposure definition
Options:
- overwrite: for fields with value of undefined, if default value is provided from Entity definition, then set this field value of input object with default value
// Require baiji-entity module
const Entity = require('baiji-entity');
// Define userEntity
const userEntity = new Entity({
name: { type: 'string' },
city: { type: 'string' },
age: { type: 'number', default: 0 },
gender: { type: 'string', default: 'unknown' },
isAdult: [{ type: 'boolean', default: false }, function(obj, options) {
return (obj && obj.age >= 18 ? true : false);
}],
points: { type: 'number', value: 100, if: function(obj, options) { return obj && obj.age >= 18; } },
description: { as: 'introduction', type: 'string', default: '' },
isSignedIn: {
type: 'boolean',
get(obj, options) {
return (options && options.isSignedIn ? true : false);
}
},
birthday: { default: '', type: 'date', format: 'iso' }
});
// Parse source data
userEntity.parse({
name: 'Felix Liu',
age: 18,
city: 'Shanghai',
birthday: new Date('2015-10-10 10:00:00'),
description: 'A programmer who lives in Shanghai',
password: 'xxxxxxx'
}, { isSignedIn: true });
// The parsed output will be as below ⬇️
{
name: 'Felix Liu',
city: 'Shanghai',
age: 18,
gender: 'unknown',
isAdult: true,
points: 100,
introduction: 'A programmer who lives in Shanghai',
isSignedIn: true,
birthday: '2015-10-10T02:00:00.000Z'
}
MIT