npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

web-serializer

v1.0.1

Published

JavaScript web serializer

Downloads

1

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
  • 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}
*/