shelving
Version:
Toolkit for using data in JavaScript.
27 lines (26 loc) • 1.06 kB
JavaScript
import { ValueFeedback } from "../feedback/Feedback.js";
import { isItem } from "../util/array.js";
import { getEntity } from "../util/entity.js";
import { OPTIONAL } from "./OptionalSchema.js";
import { StringSchema } from "./StringSchema.js";
/** Validate a file name matching one or more extensions. */
export class EntitySchema extends StringSchema {
types;
constructor({ types, title = "Entity", ...options }) {
super({ title, ...options });
this.types = types;
}
validate(unsafeValue = this.value) {
const entity = super.validate(unsafeValue);
const [type] = getEntity(entity);
if (!type)
throw new ValueFeedback("Must be entity", unsafeValue);
if (this.types && !isItem(this.types, type))
throw new ValueFeedback("Invalid entity type", type);
return entity;
}
}
/** Valid file, e.g. `challenge:a1b2c3` */
export const ENTITY = new EntitySchema({});
/** Valid optional file, e.g. `file.txt`, or `null` */
export const OPTIONAL_ENTITY = OPTIONAL(ENTITY);