UNPKG

2.21 kBTypeScriptView Raw
1import { Request, ValidationError } from './base';
2/**
3 * Given a validation error, returns a new value that represents it.
4 */
5export type ErrorFormatter<T = any> = (error: ValidationError) => T;
6type ToArrayOptions = {
7 /**
8 * Whether only the first error of each field should be returned.
9 * @default false
10 */
11 onlyFirstError?: boolean;
12};
13export type ResultFactory<T> = (req: Request) => Result<T>;
14interface ResultFactoryBuilderOptions<T = any> {
15 /**
16 * The default error formatter of every {@link Result} instance returned by
17 * the custom `validationResult()` function.
18 */
19 formatter: ErrorFormatter<T>;
20}
21/**
22 * Extracts the validation errors of an express request
23 */
24export declare const validationResult: ResultFactory<ValidationError> & {
25 withDefaults: typeof withDefaults;
26};
27/**
28 * The current state of the validation errors in a request.
29 */
30export declare class Result<T = any> {
31 private formatter;
32 private readonly errors;
33 constructor(formatter: ErrorFormatter<T>, errors: readonly ValidationError[]);
34 /**
35 * Gets the validation errors as an array.
36 *
37 * @param options.onlyFirstError whether only the first error of each
38 */
39 array(options?: ToArrayOptions): T[];
40 /**
41 * Gets the validation errors as an object.
42 * If a field has more than one error, only the first one is set in the resulting object.
43 *
44 * @returns an object from field name to error
45 */
46 mapped(): Record<string, T>;
47 /**
48 * Specifies a function to format errors with.
49 * @param formatter the function to use for formatting errors
50 * @returns A new {@link Result} instance with the given formatter
51 */
52 formatWith<T2>(formatter: ErrorFormatter<T2>): Result<T2>;
53 /**
54 * @returns `true` if there are no errors, `false` otherwise
55 */
56 isEmpty(): boolean;
57 /**
58 * Throws an error if there are validation errors.
59 */
60 throw(): void;
61}
62/**
63 * Creates a `validationResult`-like function with default options passed to every {@link Result} it
64 * returns.
65 */
66declare function withDefaults<T = any>(options?: Partial<ResultFactoryBuilderOptions<T>>): ResultFactory<T>;
67export {};