UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

49 lines (48 loc) 1.68 kB
import { ValueError } from "../error/ValueError.js"; import { Feedback } from "../feedback/Feedback.js"; import { UNDEFINED } from "../util/validate.js"; /** * An abstract API resource definition, used to specify types for e.g. serverless functions.. * * @param name The name of the resource, e.g. `getUser`. * @param payload The `Validator` the resource's payload must conform to (defaults to `undefined` if not specified). * @param returns The `Validator` the resource's returned value must conform to (defaults to `undefined` if not specified). */ export class Resource { /** Resource name.. */ name; /** Payload validator. */ payload; /** Result validator. */ result; constructor(name, payload = UNDEFINED, result = UNDEFINED) { this.name = name; this.payload = payload; this.result = result; } /** * Validate a payload for this resource. * * @returns The validated payload for this resource. * @throws Feedback if the payload could not be validated. */ prepare(unsafePayload) { return this.payload?.validate(unsafePayload); } /** * Validate a result for this resource. * * @returns The validated result for this resource. * @throws ValueError if the result could not be validated. */ validate(unsafeResult) { try { return this.result.validate(unsafeResult); } catch (thrown) { if (thrown instanceof Feedback) throw new ValueError(`Invalid result for resource "${this.name}"`, { received: unsafeResult, caller: this.validate }); throw thrown; } } }