Solid · guide

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.

Install it
pnpm add @niscorp/solid zod
Step 1 of 3

A shape with rules

A booking reference has a pattern, and nobody may book more than four seats.

A shape with rules
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(),
});
Step 2 of 3

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.

Ask for the check
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));
Step 3 of 3

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.

Half a value, then the whole
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()));
Then

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.

Run it
npx tsx rules.mts
It prints
half 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"}