Skip to main content
On this page

Basic Example

Basic example of data serialization

Let’s create a serializer that converts objects into binary data and vice versa. For this example, consider a hypothetical user object:

import { Serializer, ExtractObj, t } from "encodexx";
const userSerializer = new Serializer({
name: t.str,
id: t.uint32,
role: t.enumerate("admin", "user", "guest"),
info: t.optional({
age: t.uint8,
createdAt: t.date,
}),
friends: [
t.or(
t.schema({ type: t.enumerate("admin"), name: t.str, link: t.str }, "type"),
t.schema({ type: t.enumerate("user"), id: t.uint32 }, "type")
),
],
});

Tip

You can omit the second argument in t.schema(), in which case encodexx will automatically compare the objects. Learn more

Serializing the user object:

// Obtaining the type of object that the schema serializes
type TUser = ExtractObj<typeof userSerializer>;
const user: TUser = {
name: "John",
role: "admin",
id: 2,
friends: [
{ type: "admin", name: "Alice", link: "https://example.com" },
{ type: "user", id: 1 },
],
};
const encoded = userSerializer.encode(user);
console.log(encoded.buffer);

Decoding the binary data:

const decoded = userSerializer.decode(encoded);
console.log(decoded);