shelving
Version:
Toolkit for using data in JavaScript.
33 lines (32 loc) • 1.42 kB
JavaScript
import { isDictionary } from "../util/dictionary.js";
import { formatArray } from "../util/format.js";
import { validateDictionary } from "../util/validate.js";
import { Schema } from "./Schema.js";
/** Validate a dictionary object (whose props are all the same with string keys). */
export class DictionarySchema extends Schema {
items;
min;
max;
constructor({ items, one = items.one, many = items.many, placeholder = `No ${many}`, min = 0, max = Number.POSITIVE_INFINITY, title = "Items", value = {}, ...options }) {
super({ one, many, title, placeholder, value, ...options });
this.items = items;
this.min = min;
this.max = max;
}
validate(unsafeValue = this.value) {
if (!isDictionary(unsafeValue))
throw "Must be object";
const validDictionary = validateDictionary(unsafeValue, this.items);
const length = Object.keys(validDictionary).length;
if (length < this.min)
throw length ? `Minimum ${this.min} ${this.many}` : "Required";
if (length > this.max)
throw `Maximum ${this.max} ${this.many}`;
return validDictionary;
}
format(dict) {
return formatArray(Object.values(dict).map(v => this.items.format(v)), undefined, this.format);
}
}
/** Valid dictionary object with specifed items. */
export const DICTIONARY = (items) => new DictionarySchema({ items });