UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

69 lines (68 loc) 2.3 kB
import { formatValue } from "../util/format.js"; import { PASSTHROUGH } from "../util/function.js"; import { getNull } from "../util/null.js"; import { getUndefined } from "../util/undefined.js"; /** * Schema is an object instance with a `validate()` method. * - Type `T` represents the type of value `validate()` returns. * - `validate()` returns `Invalid` if value was not valid. */ export class Schema { /** String for one of this thing, e.g. `product` or `item` or `sheep` */ one; /** String for several of this thing, e.g. `products` or `items` or `sheep` (defaults to `one` + "s") */ many; /** Title of the schema, e.g. for using as the title of a corresponding field. */ title; /** Description of the schema, e.g. for using as a description in a corresponding field. */ description; /** Placeholder of the schema, e.g. for using as a placeholder in a corresponding field. */ placeholder; /** Default value for the schema if `validate()` is called with an `undefined` value. */ value; constructor({ one = "value", many = `${one}s`, title, description, placeholder, value }) { this.one = one; this.many = many; this.title = title; this.description = description; this.placeholder = placeholder; this.value = value; } /** Format a validated value of this type as a string. */ format(value) { return formatValue(value, undefined, this.format); } } // Unknown validator always passes through its input value as `unknown` export const UNKNOWN = { one: "value", many: "values", title: "Value", description: undefined, placeholder: undefined, value: undefined, validate: PASSTHROUGH, format: formatValue, }; // Undefined validator always returns `undefined` export const UNDEFINED = { one: "none", many: "none", title: "None", description: undefined, placeholder: undefined, value: undefined, validate: getUndefined, format: () => formatValue(undefined), }; // Null validator always returns `null` export const NULL = { one: "none", many: "none", title: "None", description: undefined, placeholder: undefined, value: null, validate: getNull, format: () => formatValue(null), };