UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

26 lines (25 loc) 977 B
import { isArrayItem } from "../util/array.js"; import { getEntity } from "../util/entity.js"; import { NULLABLE } from "./NullableSchema.js"; import { StringSchema } from "./StringSchema.js"; /** Validate a file name matching one or more extensions. */ export class EntitySchema extends StringSchema { types; constructor({ one = "entity", title = "Entity", types, ...options }) { super({ one, title, ...options }); this.types = types; } validate(unsafeValue = this.value) { const entity = super.validate(unsafeValue); const [type] = getEntity(entity); if (!type) throw "Must be entity"; if (this.types && !isArrayItem(this.types, type)) throw "Invalid entity 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 NULLABLE_ENTITY = NULLABLE(ENTITY);