Check a value when it is finished
A rule such as a pattern or a maximum cannot be judged on half a value. Solid can check it when the value is finished.
pnpm add @niscorp/solid zodA shape with rules
A booking reference has a pattern, and nobody may book more than four seats.
import { z } from 'zod';
import { createStream } from '@niscorp/solid';
const Booking = z.object({
reference: z.string().regex(/^B-\d{4}$/),
seats: z.number().max(4),
name: z.string(),
});Ask for the check
Without an initial value Solid builds one from the schema, and an empty reference would not pass the pattern. So the stream is given one that does.
constraints: 'finalize' runs the schema’s rules on each value when it is finished. By default Solid checks the kind of each value and that its key is in your schema.
const stream = createStream({
schema: Booking,
initial: { reference: 'B-0000', seats: 1, name: '' },
constraints: 'finalize',
});
stream.onError((error) => console.log(error.path || '(the whole booking)', '·', error.phase, '·', error.message));Half a value, then the whole
B-20 does not match the pattern, and nothing is said: it is not finished. Six seats is said when the name of the next key has been read.
The value is reported, and it stays. What to do with it is yours to decide.
stream.write('{"reference":"B-20');
console.log('half a reference:', stream.current().reference);
stream.write('41","seats":6,"name":"Ada"}');
console.log(JSON.stringify(stream.current()));Run it.
No error for the half reference. Then the six seats are reported, at seats and again for the whole booking when it closes, and the last line shows the 6 still there.
npx tsx rules.mtshalf a reference: B-20
seats · finalize · Too big: expected number to be <=4
(the whole booking) · finalize · Too big: expected number to be <=4
{"reference":"B-2041","seats":6,"name":"Ada"}