egg-serializer
v1.1.0
Published
serializer any data to response
Downloads
8
Readme
egg-serializer
serializer any data to response
Install
$ npm i egg-serializer --save
Usage
// {app_root}/config/plugin.js
exports.serializer = {
enable: true,
package: 'egg-serializer',
};
Example
ctx.serialize
in Controller
ctx.body = ctx.serialize('api.user', user);
// with options
ctx.body = ctx.serialize('api.search', searchResult, { foo: 'bar' });
Serializers
Easy way, exports fields
module.exports = [
'name',
'age',
];
Simple way, only provider fields
// {app_root}/app/serializer/user.js
module.exports = app => {
return class extends app.Serializer {
get fields() {
return [
'name',
'age',
// ... and so on
];
}
}
};
Custom way, override format method
// {app_root}/app/serializer/api/search.js
module.exports = app => {
return class extends app.Serializer {
constructor() {
super();
this.fields = [
'count',
'time',
// ... and so on
];
}
format(obj, options) {
const data = this.pick(obj);
data.book = app.serialize('api.book', obj.book);
data.user = app.serialize('api.user', obj.user);
data.last_editor = app.serialize('api.user', obj.last_editor);
data.server_time = Date.now();
if (options.foo === 'bar') {
data.foo = 'bar';
}
return data;
},
}
};
Configuration
// {app_root}/config/config.default.js
exports.serializer = {
// show `_serializer` property on data
showSerializerType: false,
};
see config/config.default.js for more detail.
Questions & Suggestions
Please open an issue here.