serializer/doc/usage.md

58 lines
1.1 KiB
Markdown
Raw Permalink Normal View History

2021-07-18 21:12:32 +00:00
## Import
In deno:
```typescript
import { Serializer } from "https://js.thunderk.net/serializer/mod.ts";
```
In browser:
```html
<script type="module">
import { Serializer } from "https://js.thunderk.net/serializer/mod.js";
</script>
2021-07-18 21:12:32 +00:00
```
## Use
Suppose you have 2 classes Class1 and Class2, whose instances you want to
serialize:
```typescript
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
```