1
0
Fork 0
Serializer of Javascript data, with objects reconstruction
Go to file
Michaël Lemaire 95b3cf9fcc Allow to serialize reference to a constructor in the namespace 2021-08-15 19:11:32 +02:00
doc Allow to serialize reference to a constructor in the namespace 2021-08-15 19:11:32 +02:00
.editorconfig Switched to deno 2020-05-13 11:18:22 +02:00
.gitignore Switched to deno 2020-05-13 11:18:22 +02:00
README.md Allow to serialize reference to a constructor in the namespace 2021-08-15 19:11:32 +02:00
TODO.md Allow to serialize reference to a constructor in the namespace 2021-08-15 19:11:32 +02:00
mod.ts Support Map and Set objects 2021-07-18 23:12:32 +02:00
run Support Map and Set objects 2021-07-18 23:12:32 +02:00
serializer.test.ts Allow to serialize reference to a constructor in the namespace 2021-08-15 19:11:32 +02:00
serializer.ts Allow to serialize reference to a constructor in the namespace 2021-08-15 19:11:32 +02:00
tsconfig.json Switched to deno 2020-05-13 11:18:22 +02:00

README.md

typescript/serializer

Build Status

About

This library offers a generic serialization system for Javascript.

Deep objects state may be serialized to a string, and reconstructed back.

Supported data types include:

  • Primitive types (number, bool, string...)
  • Set and Map standard objects
  • Class instances, as long as the class list is exhaustively provided to the serializer

Be warned that the resulting serialized value may be quite large and uncompressed.

Import

In deno:

import { Serializer } from "https://js.thunderk.net/serializer/mod.ts";

In browser:

<script type="module">
import { Serializer } from "https://js.thunderk.net/serializer/mod.js";
</script>

Use

Suppose you have 2 classes Class1 and Class2, whose instances you want to serialize:

Class1 { /* [...] */ }
Class2 { /* [...] */ }

// Here is the example object we want to serialize to a string
const obj = {
  a: [1, "a", new Class1()],
  b: new Class2("x"),
  c: new Class3(),
};

// We prepare the serializer, providing the class namespace
const namespace = {
  Class1,
  Class2,
};
const serializer = new Serializer(namespace);

// Optionally, some class instances may be ignored (they will be replaced by *undefined*)
serializer.addIgnoredClass(Class3);

// Serialize the object to a string
const state = serializer.serialize(obj);

// Reconstruct the object back
const nobj = serializer.unserialize(state);

console.log(nobj.a[0]);
// output: 1

console.log(nobj.b instance of Class2);
// output: true

console.log(nobj.c);
// output: undefined