@sebbia/object-deserializer
TypeScript icon, indicating that this package has built-in type declarations

0.4.0 • Public • Published

Typesafe Object Deserializer

badge

This is a simple and lightweight library for typesafe deserialization, convertion and validation of a POJO (Plain Old Javascript Object) which you usually receive from the server as a JSON response.

If any error occures object deserializer throws a DeserializationError with an additional information about a path to the invalid value in a POJO.

This is a simple usage example:

import * from 'object-deserializer';

type Person = {
  name: string;
  birthday?: Date;
};

const response = `
{
  "person": {
    "name": "John",
    "birthday": "1990-01-01"
  }
}`;

const person = deserialize<Person>(JSON.parse(response), d =>
  d.required('person').asObject(d => ({
    name: d.required('name').asString,
    birthday: d.optional('birthday')?.asDate,
  }))
);

You can create your own value mappers like this:

function personMapper(d: ObjectDeserializer): Person {
  return {
    name: d.required('name').asString,
    birthday: d.optional('birthday')?.asDate,
  };
}

And use it later:

const person = d.required('person').asObject(personMapper);

You can find more advanced examples in the unit tests file.

Package Sidebar

Install

npm i @sebbia/object-deserializer

Weekly Downloads

0

Version

0.4.0

License

ISC

Unpacked Size

14.4 kB

Total Files

14

Last publish

Collaborators

  • sebbia