shelving
Version:
Toolkit for using data in JavaScript.
30 lines (29 loc) • 1.3 kB
JavaScript
import { ValueFeedback } from "../feedback/Feedback.js";
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, min = 0, max = Number.POSITIVE_INFINITY, title = "Items", value = {}, ...options }) {
super({ title, value, ...options });
this.items = items;
this.min = min;
this.max = max;
}
validate(unsafeValue = this.value) {
if (!isDictionary(unsafeValue))
throw new ValueFeedback("Must be object", unsafeValue);
const validDictionary = validateDictionary(unsafeValue, this.items);
const length = Object.keys(validDictionary).length;
if (length < this.min)
throw new ValueFeedback(length ? `Minimum ${this.min} items` : "Required", validDictionary);
if (length > this.max)
throw new ValueFeedback(`Maximum ${this.max} items`, validDictionary);
return validDictionary;
}
}
/** Valid dictionary object with specifed items. */
export const DICTIONARY = (items) => new DictionarySchema({ items });