Schema APIs
@livon/schema exports schema builders and schema combinators.
This section documents each schema API with a focused usage example.
Use it as the reference when implementing or reviewing schema definitions.
Foundations
Primitive schemas
Collection schemas
Combinators
API schemas
Complete example (all schema APIs)
import {
after,
and,
api,
array,
before,
binary,
boolean,
date,
enumeration,
literal,
number,
object,
operation,
or,
string,
subscription,
tuple,
union,
} from '@livon/schema';
const Author = string().min(2);
const MessageText = string().min(1);
const Priority = number().int().min(0);
const IsPinned = boolean();
const CreatedAt = date();
const Role = enumeration('Role').values('user', 'moderator', 'admin');
const Tags = array({name: 'Tags', item: string()});
const Position = tuple({name: 'Position', items: [number(), number()]});
const GlobalRoom = literal({name: 'GlobalRoom', value: 'global'});
const Attachment = binary({name: 'Attachment'});
const TextOrAttachment = union({
name: 'TextOrAttachment',
options: [MessageText, Attachment],
});
const RoomSelector = or({
name: 'RoomSelector',
options: [GlobalRoom, string()],
});
const NormalizedText = before({
schema: MessageText,
hook: (input) => (typeof input === 'string' ? input.trim() : input),
});
const LowerText = after({
schema: NormalizedText,
hook: (value) => value.toLowerCase(),
});
const MessageInput = object({
name: 'MessageInput',
shape: {
author: Author,
text: NormalizedText,
payload: TextOrAttachment,
room: RoomSelector,
priority: Priority,
isPinned: IsPinned,
createdAt: CreatedAt,
role: Role,
tags: Tags,
position: Position,
},
});
const WithId = object({
name: 'WithId',
shape: {
id: string(),
},
});
const MessageWithId = and({
left: MessageInput,
right: WithId,
name: 'MessageWithId',
});
const sendMessage = operation({
input: MessageInput,
output: MessageWithId,
exec: async (input) => ({
...input,
text: LowerText.parse(input.text),
payload: input.text,
id: 'msg-1',
}),
publish: {
onMessage: (output) => output,
},
});
const OnMessage = subscription({
payload: MessageWithId,
});
const ApiSchema = api({
operations: {sendMessage},
subscriptions: {onMessage: OnMessage},
});
export const serverSchema = ApiSchema;
Parameters
The complete example intentionally stays compact. Each function parameter used above is documented on its dedicated schema page:
- primitives and collections: string, number, boolean, date, enumeration, object, array, tuple, literal, union, or, binary
- combinators: before, after, and
- schemas: api, operation, subscription, fieldResolver