web-serializer
v1.0.1
Published
JavaScript web serializer
Downloads
1
Maintainers
Readme
web-serializer
JavaScript web serializer - async, parallel, lightweight
Installation
npm install --save web-serializer
Documentation
Let's start with an example.
Remark: you are welcome to review the unit-tests to get more usage examples and specification on Github
Imagine a NodeJS service exposing APIs for querying books' information, stored in MongoDB and some other integrated web services. This module allows to create serializers to easily modify the data structure + add new fields calculated or even async retrieved using other custom Web Serializers
Here is how one could use a serializer preparing an object to be passed to express's req.json
method for book entity exposing name, code, author.name
Our express based router would look like:
const serializersBooks = require('@serializers/books');
router.get('books', async (req, res) => {
const books = await getBooksPagefrom(req.query); // e.g. from MongoDB
res.json(
await serializersBooks.serializeEach(books); // serializeEach - we want each list's item to be serialized
);
};
router.get('books/:id', async (req, res) => {
const book = await getBookById(req.params.id);
res.json(
await serializersBooks.serialize(book);
);
};
And here is how such a serializer can be implemented using the web-serializer module:
const Serializer = require('serializer');
const serializersReviews = require('@serializers/books');
const whiteList = [
'name', 'code', 'author.name',
{
preview: {
calc: (obj, serOptions) => {
if (!serOptions.withPreview) {
return;
}
return obj.preview;
}
},
reviews: {
calc: async (obj, serOptions) => {
// using a serializer inside a serializer - why not?! :)
// it could retrieve the list of reviews from a reviews service by book ID
// and then serialize each of them
return serializersReviews.serializeEach(obj.id, serOptions);
}
},
},
];
module.exports = new Serializer({whiteList});
Usage
Please check the example above. Use serialize
method to serialize one entity and serializeEach
method to serialize an array of entities, while all the entities and all the async calc methods are processed in an asynchronous way providing the best performance.
The second parameter of serialize
and serializeEach
methods is serOptions - this object can be used in calc
(sync or async calculated fields) to provide meta data or payload.
Serializer defenition
const Serializer = require('serializer');
const mySerializer = new Serializer({whiteList: [...], blackList: [...]});
- whiteList - an array the fields/paths of the result object. There are few ways to define those (which can be combined within the same serializer):
- fields' name/path. E.g.
['name', 'code', 'author.name']
could result in{name: 'My advantures', code: 'ad2344', author: {name: 'John Brown'}}
- calc - useful when the field's value should be calculated - supports also async functions. Check
preview
from the example above - path - get value/s by a path from the object
- allFromPathWithoutNameSpace - merges a sub-object of the input object into the root of the result object
- fields' name/path. E.g.
- blackList - the list of the fields/paths to be omitted on the result object. blackList is applied after whiteList, so it overwrites the whitelist's directive if a field is mentioned in both whiteList and blackList. Combining whiteList and blackList can be useful when you want to whiteList a namespace, but omit some sub-objects of it.
Examples
fields' name/path
const config = {whiteList: ['foo', 'baz']};
const serializer = new Serializer(config);
const result = serializer.serialize({foo: 2, bar: 3, baz: {yoo: 4, quz: 7}});
// result: {foo: 2, baz: {yoo: 4}}
calc
const config = {
whiteList: [
'foo',
{
bar: {calc: (obj) => 6 * obj.foo},
},
{
baz: {calc: async (obj) => simulateAsyncCallout(7 * obj.foo)},
},
],
};
const serializer = new Serializer(config);
const result = await serializer.serialize({
foo: 2,
yoo: 3,
});
/*
result: {
foo: 2,
bar: 12,
baz: 14,
}
*/
path
const config = {
whiteList: [
'foo',
{
bar: {path: 'a.b'},
},
{
baz: {path: 'a.d[1]'},
},
],
};
const serializer = new Serializer(config);
const result = await serializer.serialize({
foo: 2,
a: {b: {c: 1}, d: [{e: 4}, {f: 5}]},
yoo: 3,
});
/*
result: {
foo: 2,
bar: {c: 1},
baz: {f: 5},
}
*/
allFromPathWithoutNameSpace
const config = {
whiteList: [
'foo',
{
whatever: {allFromPathWithoutNameSpace: 'a.b'},
},
],
};
const serializer = new Serializer(config);
const result = await serializer.serialize({
foo: 2,
a: {b: {c: 1, d: [{e: 4}, {f: 5}]}},
yoo: 3,
});
/*
result: {
foo: 2,
c: 1, d: [{e: 4}, {f: 5}],
}
*/
blackList
const config = {
whiteList: [
'foo',
{
bar: {allFromPath: 'a.b'},
},
],
blackList: ['bar.d'],
};
const serializer = new Serializer(config);
const result = await serializer.serialize({
foo: 2,
a: {b: {c: 1, d: [{e: 4}, {f: 5}]}},
yoo: 3,
});
/*
result: {
foo: 2,
bar: {c: 1},
}
*/
serializeEach
const config = {whiteList: ['foo', 'baz']};
const serializer = new Serializer(config);
const result = await serializer.serializeEach([
{foo: 2, bar: 3, baz: 4},
{foo: 3, bar: 7, baz: 13},
]);
/*
result: [
{foo: 2, baz: 4},
{foo: 3, baz: 13},
]
*/
serOptions.beforeEach
const config = {
whiteList: ['foo',
{
quz: {
calc: async (obj, serOptions) => serOptions._payload.bar + serOptions._payload.baz,
},
qux: {
calc: async (obj, serOptions) => serOptions._payload.bar - serOptions._payload.baz,
},
},
],
};
const serOptions = {
beforeEach: [
async (obj, serOptions) => {
const bar = await simulateAsyncCallout(37);
serOptions._payload = serOptions._payload || {};
serOptions._payload.bar = bar;
return obj;
},
async (obj, serOptions) => {
const baz = await simulateAsyncCallout(53);
serOptions._payload = serOptions._payload || {};
serOptions._payload.baz = baz;
return obj;
},
],
};
const serializer = new Serializer(config);
const result = await serializer.serialize({foo: 2}, serOptions));
/*
result: {foo: 2, quz: 90, qux: -16}
*/
using serOptions for serialization settings
const config = {
whiteList: [
'foo',
{
bar: {
calc: (obj, serOptions) => {
if (serOptions.reduced) {
return;
}
return 6 * obj.foo;
}
},
},
],
};
const serializer = new Serializer(config);
const result1 = await serializer.serialize({foo: 2, yoo: 3});
const result2 = await serializer.serialize({foo: 2, yoo: 3}, {reduced: true});
/*
result1: {foo: 2, bar: 12}
result1: {foo: 2, bar: undefined}
*/