UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

29 lines (28 loc) 1.25 kB
import { isDictionary } from "../util/dictionary.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; } } /** Valid dictionary object with specifed items. */ export const DICTIONARY = (items) => new DictionarySchema({ items });