Get Started
Introduction
The serializer is a library that allows you to serialize instances of classes to objects. It is designed to be used in Project Graph to save and load projects.
This package provides few decorators to make it easy to flag properties and methods that should be serialized, and to customize how to pass arguments to the constructor when deserializing.
Requirements
You need to enable experimentalDecorators and emitDecoratorMetadata in your tsconfig.json.
Installation
npm install @graphif/serializer
# or use pnpm
pnpm add @graphif/serializerBasic Usage
Here is a class Person:
class Person {
private isGreeting: boolean = false;
constructor(
public name: string,
public age: number,
) {}
greet() {
this.isGreeting = true;
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
this.isGreeting = false;
}
}We want to include name and age in the serialized object, but not isGreeting. We can use the @serializable decorator to flag name and age as serializable:
Because of technical limitations, you cannot use the @serializable decorator on arguments of the constructor.
import { serializable } from "@graphif/serializer";
class Person {
@serializable
public name: string;
@serializable
public age: number;
private isGreeting: boolean = false;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
this.isGreeting = true;
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
this.isGreeting = false;
}
}Now we can serialize an instance of Person to an object:
import { serialize } from "@graphif/serializer";
const person = new Person("Alice", 25);
const serialized = serialize(person);
console.log(serialized);This will output the serialized object, without prototypes:
{
"_": "Person",
"name": "Alice",
"age": 25
}You can save this object via JSON.stringify or MsgPack.
Every object (including nested) has a _ property that contains the name of the class. This is used to determine the
class when deserializing.
We can also deserialize the object back to an instance of Person:
import { deserialize } from "@graphif/serializer";
const deserialized = deserialize(serialized);
console.log(deserialized);This will output:
Person { name: "Alice", age: 25 }