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

tree-house-serializer

v1.3.0

Published

Json de/serialization made for consistency

Downloads

2

Readme

Tree-house serializer

De/serialize json for consistency!

npm version Dependencies Build Status Coverage Status Greenkeeper badge

Added changes vs 'jsonade'

  • Library fully rewritten in Typescript
  • Allow asynchronous functions in .serialize

Installation

npm install tree-house-serializer

Serializer

constructor

const mySerializer = new Serializer(resource, configuration, options);

Arguments

resource (string): Name of the resource being serialized

configuration (Object): Configuration for serialisation

options (Object): Extra options for the serializer (optional)

Configuration:

  • attributes (Array): attributes to serialize

Options:

  • case: Convert the case of the keys of data
  • Undefined: Doesn't convert the case
  • camelCase: Converts keys to camelCase
  • snake_case: Converts keys to snake_case
  • kebab-case: Converts keys to kebab-case

Returns

Returns an instance of a custom serializer, ready to use for serializing data.

Serializer instance

serialize - asynchronous

await mySerializer.serialize(data, configuration);

Arguments

data (Object|Array): Dataset to serialize.

configuration (Object): Configuration for serialisation

  • totalCount (Number) *optional: When serializing an array, the totalCount is part of the meta object. If no totalCount is configured, the length of the provided dataset is used.

Besides totalCount, configuration may be used to extend the meta response object with arbitrary keys. The type key however, cannot be overwritten.

Returns

Returns a serialized data respresentation of the given data.

ErrorSerializer

serialize

Arguments

error (Object|Array): Error(s) to serialize.

const errors = ErrorSerializer.serialize([error]);

Returns

  • errors (Object): object containing multiple errors.

Every error can have these properties:

| key | | |---|---| | status | required | | title | required | | id | optional | | code | optional, application specific | | detail | optional | | meta | optional |

Example
{
  "errors": [
    {
      "id": "ba4b9f14-5b83-4dfd-ac46-1c3868e1b3ec",
        "status": 400,
        "code": "2006",
        "title": "Article not found",
        "detail": "Article with id 892bb574-090d-4d63-a5b5-cb928d5f5c5f not found",
        "meta": {
          "stack": "NotFoundError: ..."
        }
    }
  ]
}

Examples

Basic example

Create a serializer

const { Serializer } = require('tree-house-serializer');

const userSerializer = new Serializer('user', {
  attributes: ['firstName', 'lastName', 'address'],
  address: {
    attributes: ['street', 'number'],
  },
});

Serialize a single resource

const data = {
  firstName: 'John',
  lastName: 'Doe',
  age: 27,
  address: {
    street: 'Markt',
    number: '100',
    city: 'Zonnedorp',
    country: 'Belgium',
  },
};

const result = await userSerializer.serialize(data);

// result:
// {
//   meta: {
//     type: 'user'
//   },
//   data: {
//     firstName: 'John',
//     lastName: 'Doe',
//     address: {
//       street: 'Markt',
//       number: '100',
//     }
//   }
// }

Serialize a list of resources

const data = [
	{
	  firstName: 'John',
	  lastName: 'Doe',
	  age: 27,
	  address: {
	    street: 'Markt',
	    number: '100',
	    city: 'Zonnedorp',
	    country: 'Belgium',
	  },
	}, {
	  firstName: 'Jessie',
	  lastName: 'Doe',
	  age: 26,
	  address: {
	    street: 'Marketstreet',
	    number: '101',
	    city: 'Sunvillage',
	    country: 'United Kingdom',
	  },
	}
];

const result = await userSerializer.serialize(data, { totalCount: 91 });

// result:
// {
//   meta: {
//     type: 'user',
//     count: 2,
//     totalCount: 91
//   },
//   data: [
//     {
//       firstName: 'John',
//       lastName: 'Doe',
//       address: {
//         street: 'Markt',
//         number: '100'
//       }
//     },
//     { ... },
//   ]
// }

Extend the meta object

const data = [
	{
	  firstName: 'John',
	  lastName: 'Doe',
	  age: 25,
	  address: {
	    street: 'Markt',
	    number: '100',
	    city: 'Zonnedorp',
	    country: 'Belgium',
	  },
	}, {
	  firstName: 'Jessie',
	  lastName: 'Doe',
	  age: 27,
	  address: {
	    street: 'Marketstreet',
	    number: '101',
	    city: 'Sunvillage',
	    country: 'United Kingdom',
	  },
	}
];

const result = await userSerializer.serialize(data, { totalCount: 91, averageAge: 26 });

// result:
// {
//   meta: {
//     type: 'user',
//     count: 2,
//     totalCount: 91
//     averageAge: 26
//   },
//   data: [
//     {
//       firstName: 'John',
//       lastName: 'Doe',
//       address: {
//         street: 'Markt',
//         number: '100'
//       }
//     },
//     { ... },
//   ]
// }

Example using a nested serializer

const { Serializer } = require('tree-house-serializer');

const addressSerializer = new Serializer('address', {
  attributes: ['street', 'number'],
});

const userSerializer = new Serializer('user', {
  attributes: ['firstName', 'lastName', 'address'],
  address: addresssSerializer,
});

const data = {
  firstName: 'John',
  lastName: 'Doe',
  age: 27,
  address: {
    street: 'Markt',
    number: '100',
    city: 'Zonnedorp',
    country: 'Belgium',
  },
};

const result = await userSerializer.serialize(data);

// result:
// {
//   meta: {
//     type: 'user'
//   },
//   data: {
//     firstName: 'John',
//     lastName: 'Doe',
//     address: {
//       street: 'Markt',
//       number: '100'
//     }
//   }
// }

Example using a case option

const { Serializer } = require('tree-house-serializer');

const userSerializer = new Serializer(
  'user', 
  { attributes: ['firstName', 'lastName', 'age', 'greeting'] },
  { case: 'snake_case' },
);

const data = {
  firstName: 'John',
  lastName: 'Doe',
  age: '27',
};

const result = await userSerializer.serialize(data);

// result:
// {
//   meta: {
//     type: 'user'
//   },
//   data: {
//     first_name: 'John',
//     last_name: 'Doe',
//     age: '27 years old'
//     greeting: 'Hello, I\'m John Doe',
//   }
// }

Example using a function to transform one property

const { Serializer } = require('tree-house-serializer');

const userSerializer = new Serializer('user', {
  attributes: ['firstName', 'lastName', 'age', 'greeting'],
  age: val => `${val} years old`,
  greeting: (v, data) => `Hello, I'm ${data.firstName} ${data.lastName}`,
});

const data = {
  firstName: 'John',
  lastName: 'Doe',
  age: '27',
};

const result = await userSerializer.serialize(data);

// result:
// {
//   meta: {
//     type: 'user'
//   },
//   data: {
//     firstName: 'John',
//     lastName: 'Doe',
//     age: '27 years old'
//     greeting: 'Hello, I\'m John Doe',
//   }
// }

Example serializing an error

const { ErrorSerializer } = require('tree-house-serializer');
const errorResponse = ErrorSerializer.serialize(ex);

License

This project is licensed under the ISC License - see the LICENSE.md file for details