forked from feathersjs-ecosystem/feathers-hooks-common
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.ts
More file actions
executable file
·70 lines (60 loc) · 2.23 KB
/
validate.ts
File metadata and controls
executable file
·70 lines (60 loc) · 2.23 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { BadRequest } from '@feathersjs/errors';
import type { HookContext } from '@feathersjs/feathers';
import type { Ajv, ErrorObject as ajvErrorObject, Options as AjvOptions } from 'ajv';
import { isPromise } from '../common';
import { checkContext } from '../utils/check-context';
import { getItems } from '../utils/get-items';
import { replaceItems } from '../utils/replace-items';
export type SyncValidatorFn<H extends HookContext = HookContext> = (
values: any,
context: H,
) => { [key: string]: string } | null;
export type AsyncValidatorFn<H extends HookContext = HookContext> = (
values: any,
context: H,
) => Promise<object | null>;
export type ValidatorFn<H extends HookContext = HookContext> =
| SyncValidatorFn<H>
| AsyncValidatorFn<H>;
export type AjvOrNewable = Ajv | (new (options?: AjvOptions) => Ajv);
export interface ValidateSchemaOptions extends AjvOptions {
/**
* The hook will throw if the data does not match the JSON-Schema. error.errors will, by default, contain an array
* of error messages. You may change this with a custom formatting function. Its a reducing function which works
* similarly to Array.reduce().
*/
addNewError: (
currentFormattedMessages: any,
ajvErrorObject: ajvErrorObject,
itemsLen: number,
itemIndex: number,
) => any;
}
/**
* Validate data using a validation function.
* @see https://hooks-common.feathersjs.com/hooks.html#validate
*/
export function validate<H extends HookContext = HookContext>(validator: ValidatorFn) {
return (context: H) => {
checkContext(context, 'before', ['create', 'update', 'patch'], 'validate');
if (typeof validator !== 'function') {
throw new BadRequest('Expected validator function. (validate)');
}
const results = validator(getItems(context), context);
if (isPromise(results)) {
return results.then((convertedValues: any) => {
if (convertedValues) {
// if values have been sanitized
replaceItems(context, convertedValues);
}
return context;
});
}
// Sync function returns errors. It cannot sanitize.
if (results && Object.keys(results).length) {
// @ts-ignore
throw new BadRequest({ errors: results });
}
return context;
};
}