serializer/README.md

74 lines
1.9 KiB
Markdown
Raw Normal View History

2018-12-30 17:12:21 +00:00
tk-serializer
=============
2019-09-22 21:27:52 +00:00
2019-09-17 08:44:25 +00:00
[![pipeline status](https://gitlab.com/thunderk/tk-serializer/badges/master/pipeline.svg)](https://gitlab.com/thunderk/tk-serializer/commits/master)
[![coverage report](https://gitlab.com/thunderk/tk-serializer/badges/master/coverage.svg)](https://gitlab.com/thunderk/tk-serializer/commits/master)
[![npm version](https://img.shields.io/npm/v/tk-serializer.svg)](https://npmjs.com/tk-serializer)
[![npm size](https://img.shields.io/bundlephobia/min/tk-serializer.svg)](https://bundlephobia.com/result?p=tk-serializer)
2018-12-30 17:12:21 +00:00
About
-----
This library offers a generic serialization system for Javascript.
Deep objects state may be serialized to a string, and reconstructed back.
Class instances are reconstructed properly, as long as they are in the provided namespace. Circular references are handled.
2019-09-13 11:57:21 +00:00
Be warned that resulting serialized value may be quite large.
Typescript definitions are included.
2019-09-17 08:11:45 +00:00
Issues can be reported on [GitLab](https://gitlab.com/thunderk/tk-serializer/issues).
2019-01-14 22:30:00 +00:00
Install
-------
2019-09-13 11:57:21 +00:00
Import in node:
```shell
npm install tk-serializer
```
```javascript
import { Serializer } from "tk-serializer";
```
Import in browser:
```html
<script src="https://unpkg.com/tk-serializer"></script>
```
```javascript
const Serializer = tkSerializer.Serializer;
```
2019-01-14 22:30:00 +00:00
Use
---
2019-09-13 11:57:21 +00:00
Suppose you have 2 classes Class1 and Class2, whose instances you want to serialize:
2018-12-30 17:28:54 +00:00
2019-09-13 11:57:21 +00:00
```javascript
2018-12-30 17:12:21 +00:00
const namespace = {
Class1,
Class2
};
const obj = {
a: [1, "a", new Class1()],
b: new Class2("x"),
c: new Class3()
};
let serializer = new Serializer(namespace);
// Optionally, some class instances may be ignored (they will be replaced by *undefined*)
serializer.addIgnoredClass(Class3);
2018-12-30 17:12:21 +00:00
// Serialize the object to a string
2019-09-13 11:57:21 +00:00
let state = serializer.serialize(obj);
2018-12-30 17:12:21 +00:00
// Reconstruct the object back (*c* will be undefined)
let nobj = serializer.unserialize(state);
2018-12-30 17:31:35 +00:00
```