Skip to main content

Serializers

Serializers convert processed values back to a format suitable for output. This is optional and primarily used when you want to output values in a readable format, or if normalization produces a value that cannot be serialized.

For example, here is a timestamp schema that normalizes to milliseconds, but serializes to ISO strings:

import { Schema, SchemaResolver } from '@versionzero/schema';
const resolver = new SchemaResolver();

const timestampNormalizer = (value) => {
if (typeof value === 'number') {
if (value < 0) {
throw new Error(`Invalid negative timestamp value: ${value}`);
}
return value;
}
else if (!value || value === 'now') {
return Date.now();
}
else if (typeof value === 'string') {
let t = new Date(value).getTime()
if (isNaN(t)) {
throw new Error(`Invalid timestamp value: ${value}`);
}
return t;
}
throw new Error(`Invalid timestamp value: ${value}`);
};

const timestampSerializer = (value) => {
return new Date(value).toISOString();
};

const schema = await resolver.compile(
new Schema('object')
.property('createdAt', new Schema()
.normalizer(timestampNormalizer)
.validator(['$is-number', '$positive'])
.serializer(timestampSerializer)
)
);

const ts = await schema.process({createdAt: 'now'});

console.log(ts); // -> { createdAt: <number> }
console.log(await schema.serialize(ts)); // -> { createdAt: '<iso date>' }