Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 33x 33x 25x 8x 33x 33x 2x 1x 31x 8x | import { promisify } from 'node:util';
/** Runs user-supplied validator functions (sync, async or callback style). */
export class CustomValidators {
/**
* Calls a validator with the instance as `this`.
*
* @param instance - Instance being validated.
* @param fn - Validator function; with one parameter more than `args` it is callback style.
* @param args - Arguments passed before the callback.
* @returns The failure (message and the thrown value), or `undefined` when the validator passed.
*/
async failure(
instance: object,
fn: unknown,
args: readonly unknown[],
): Promise<Readonly<{ message: string; original: unknown }> | undefined> {
try {
await this.#call(instance, fn, args);
return undefined;
} catch (error) {
return { message: CustomValidators.#messageOf(error), original: error };
}
}
async #call(instance: object, validator: unknown, args: readonly unknown[]): Promise<void> {
const fn = validator as (...callArgs: unknown[]) => unknown;
if (fn.length === args.length + 1) {
await promisify(fn.bind(instance, ...args))();
return;
}
await fn.apply(instance, [...args]);
}
static #messageOf(error: unknown): string {
return error instanceof Error
? error.message
: typeof error === 'string' && error !== ''
? error
: 'Validation error';
}
}
|