-
Notifications
You must be signed in to change notification settings - Fork 286
/
Copy pathis.ts
53 lines (46 loc) · 1.46 KB
/
is.ts
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
import { ModelValidateOptions } from 'sequelize';
import { addAttributeOptions } from '../model/column/attribute-service';
/**
* Adds custom validator
* @param name Name of validator
* @param validator Validator function
*/
export function Is(name: string, validator: (value: any) => any): Function;
/**
* Adds custom validator
* @param validator Validator function
*/
export function Is(validator: (value: any) => any): Function;
/**
* Will only allow values, that match the string regex or real regex
*/
export function Is(
arg:
| string
| (string | RegExp)[]
| RegExp
| { msg: string; args: string | (string | RegExp)[] | RegExp }
): Function;
export function Is(...args: any[]): Function {
const options: ModelValidateOptions = {};
const argIsFunction = typeof args[0] === 'function';
if (argIsFunction || (typeof args[0] === 'string' && typeof args[1] === 'function')) {
let validator: (value: any) => any;
let name: string;
if (argIsFunction) {
validator = args[0] as (value: any) => any;
name = validator.name;
if (!name) throw new Error(`Passed validator function must have a name`);
} else {
name = args[0];
validator = args[1];
}
options[`is${name.charAt(0).toUpperCase() + name.substr(1, name.length)}`] = validator;
} else {
options.is = args[0];
}
return (target: any, propertyName: string) =>
addAttributeOptions(target, propertyName, {
validate: options,
});
}