Skip to content

JS SDK — Formatters

Formatters handle the serialization and deserialization of IonPath types to/from CBOR binary format.

IonFormatterStorage

IonFormatterStorage is a global registry that maps type identifiers to serialize/deserialize functions:

import { IonFormatterStorage } from '@nicurt/ion.webcore.js';

// Register a formatter for a custom type
IonFormatterStorage.register("User", {
    serialize(writer, value) {
        writer.writeUInt32(value.id);
        writer.writeString(value.name);
        writer.writeString(value.email);
    },
    deserialize(reader) {
        return {
            id: reader.readUInt32(),
            name: reader.readString(),
            email: reader.readString()
        };
    }
});

You don't normally write formatters manually. The compiler generates them from your .ion schema. This page documents the internals for debugging or extension purposes.

Primitive Formatters

Built-in formatters for all IonPath primitive types are registered automatically:

Ion Type JS Encoding
i1, i2, i4 CBOR signed integer (number)
i8, i16 CBOR signed integer (BigInt)
u1, u2, u4 CBOR unsigned integer (number)
u8, u16 CBOR unsigned integer (BigInt)
f2 CBOR half-precision float (number)
f4 CBOR single-precision float (number)
f8 CBOR double-precision float (number)
bool CBOR simple value (boolean)
string CBOR text string (string)
bytes CBOR byte string (Uint8Array)
guid CBOR byte string (16 bytes → string UUID)
datetime CBOR tag 0 text string (ISO 8601 → Date)
uri CBOR text string (string)

Generated Formatters

For each message in your schema, the compiler generates a formatter that serializes fields in index order:

// Generated for: msg User { id: u4; name: string; }
IonFormatterStorage.register("User", {
    serialize(writer, value) {
        writer.writeArrayHeader(2);
        writer.writeUInt32(value.id);
        writer.writeString(value.name);
    },
    deserialize(reader) {
        reader.readArrayHeader();
        return {
            id: reader.readUInt32(),
            name: reader.readString()
        };
    }
});