shelving
Version:
Toolkit for using data in JavaScript.
42 lines (41 loc) • 1.49 kB
JavaScript
import { ValueFeedback } from "../feedback/Feedback.js";
import { requireFirst } from "../util/array.js";
import { formatValue } from "../util/format.js";
import { getMap, isMapItem } from "../util/map.js";
import { Schema } from "./Schema.js";
/** Define a valid value from an allowed set of values. */
export class AllowSchema extends Schema {
allow;
constructor(options) {
const allow = getMap(options.allow);
const value = requireFirst(allow.keys());
super({ value, ...options });
this.allow = allow;
}
validate(unsafeValue = this.value) {
if (isMapItem(this.allow, unsafeValue))
return unsafeValue;
throw new ValueFeedback("Unknown value", unsafeValue);
}
/** Iterate over the the allowed options in `[key, value]` format. */
[Symbol.iterator]() {
return this.allow[Symbol.iterator]();
}
}
/** Define a valid string value from an allowed set of string values. */
export class AllowStringSchema extends AllowSchema {
constructor({ allow, ...options }) {
super({ allow: getMap(allow), ...options });
}
validator(unsafeValue = this.value) {
return super.validate(formatValue(unsafeValue));
}
}
/** Valid value from an allowed set of values. */
export function ALLOW(allow) {
return new AllowSchema({ allow });
}
/** Valid string from an allowed set of values. */
export function ALLOW_STRING(allow) {
return new AllowStringSchema({ allow });
}