Reading

Read a value with a declaration where no package takes it. Spell a value as a URL holds it, and log why a value was refused.

On this page

Reading a value

ts
import { field, read } from '@k8ordo/field';

const body = field.object({
  title: field.string({ required: true, maxLength: 80 }),
  tags: field.list(field.string()),
});

const { value, issues } = read(body, await request.json());

read takes what a place holds as it is: a string, the strings of a repeated URL parameter, or the value itself, such as JSON or a File. A kind handed several strings reads the first.

The value it returns has every refused part replaced by its default, and a list keeps only the items it read. issues lists the refusals, each with the keys and list indexes down to the value, the flag, and the declaration that refused it.

value is typed unknown, because with an issue a required value with no default is undefined. Treat it as the declaration’s type once issues is empty.

read never throws. Whether to use the value with defaults filled in, or to refuse it on its issues, is the caller’s choice.

Spelling a value for a URL

ts
import { field, write } from '@k8ordo/field';

const page = field.integer({ min: 1, default: 1 });

write(page, 2); // ['2']
write(page, 1); // []
write(field.list(field.string()), ['a', 'b']); // ['a', 'b']
write(page, '2'); // null

write turns a value into the strings a URL parameter holds: none at the default, one per item of a list, and true or false for a boolean.

It returns null for a value the declaration cannot spell: a value of another kind, or a kind no string holds, such as a file or an object. read of what write returned gives the value back.

Explaining a refusal

ts
import { explain } from '@k8ordo/field';

for (const issue of issues) {
  console.error(`${issue.path.join('.')}: ${explain(issue)}`);
}
// title: is missing

explain words a refusal in English for the developer. It never writes the refused value, so a secret never lands in a log.

It is not wording for a visitor: a form shows the declaration’s messages or its built-in words.

Flags

A refusal is named after the ValidityState flag HTML sets for the same mistake, plus tooFew and tooMany for a list’s count.

  • valueMissing: required, and the value is absent, a false boolean included.
  • typeMismatch: not the kind, such as not an email address, not a URL, or not one of an enum’s values.
  • badInput: a number, a date or a time that is not spelled as one.
  • tooShort and tooLong: text shorter than minLength, or longer than maxLength.
  • patternMismatch: text the pattern does not match.
  • rangeUnderflow and rangeOverflow: below min, or above max.
  • stepMismatch: not on step, a fraction for an integer included.
  • tooFew and tooMany: a list with fewer items than its min, or more than its max.
k8ordo

React libraries that use Baseline features without holding back.