Basic Tutorial (JavaScript)
This tutorial introduces basic CBOT usage in both untyped and typed situations.
Installation
npm i @sisujs/meta-cbot
Untyped Example: Library
CBOT can be used as a simple replacement for JSON.stringify() and
JSON.parse() and this example will demonstrate typical JSON-like behavior
that you may be accustomed to. The example consists of a library with three
concepts: Author, Book and Catalog.
Let's define some values:
const isaac = {
name: "Isaac Asimov",
birthdate: Temporal.PlainDate.from("1920-01-02")
}
const foundation = {
title: "Foundation",
isbn: "978-0-394-51330-7",
publicationYear: 1951,
author: isaac
}
const iRobot = {
title: "I, Robot",
isbn: "978-0-394-51331-4",
publicationYear: 1950,
author: isaac
}
const catalog = [
{
genre: "Science Fiction",
books: [
foundation,
iRobot
],
authors: new Set([isaac])
}
]
In order to serialize something, one needs an instance of CBOT in some static variable. You should always create just one instance for each model and use it globally.
import { CBOT } from "@sisujs/common"
const cbot = Cbot.getInstance({
temporalApiEnabled: true
})
Now we can actually serialize an object to a message and vice versa:
const msg = cbot.serialize(foundation);
const deserialized = cbot.deserialize(msg);
So, this example demonstrated how serialization and deserialization are used in a JSON-like way.
Use of Temporal API
This example uses Temporal.PlainDate for storing birthdate.
Check Supported Types how to enable the
feature.
Using Untyped Model
Adding Untyped Model creates an opportunity to reduce message size by sharing common static keys by both sender and receiver. This mode is initialized as follows:
const cbot = CBOT.getInstance({
staticKeys: [
'name',
'birthdate',
'title',
'isbn',
'author',
'publicationYear',
'books',
'genre',
'authors'
]
});
Even though CBOT is now instantiated with shared static keys, that does not prevent from creating new Key-ID Pairs when needed during serialization. The instance can now be used in the same way as in previous example.
Note that in this mode, both parties must be configured in the same way, otherwise deserialization will fail.