-
Notifications
You must be signed in to change notification settings - Fork 567
/
rule.ts
66 lines (62 loc) · 1.71 KB
/
rule.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
54
55
56
57
58
59
60
61
62
63
64
65
66
import * as Joi from 'joi';
import {
attachClassMetadata,
getClassMetadata,
getPropertyType,
} from '@midwayjs/core';
import { RULES_KEY } from '../constants';
/**
* @deprecated
*/
export interface RuleOptions {
required?: boolean;
min?: number;
max?: number;
}
export function Rule(
rule: Joi.AnySchema<any>
): PropertyDecorator & ClassDecorator;
/**
* @deprecated
*/
export function Rule(
rule: new (...args) => any,
options?: RuleOptions
): PropertyDecorator & ClassDecorator;
export function Rule(
rule: Joi.AnySchema<any> | (new (...args) => any),
options: RuleOptions = { required: true }
): ClassDecorator & PropertyDecorator {
return function (target, propertyKey?) {
if (propertyKey) {
// property decorator
if (!Joi.isSchema(rule)) {
// 老代码,待废弃
rule = Joi.object(getClassMetadata(RULES_KEY, rule)).meta({
id: rule.name,
});
if (getPropertyType(target, propertyKey).name === 'Array') {
rule = Joi.array().items(rule);
if (options.min) {
rule = (rule as Joi.ArraySchema<any>).min(options.min);
}
if (options.max) {
rule = (rule as Joi.ArraySchema<any>).max(options.max);
}
}
if (options.required) {
rule = rule.required();
}
}
attachClassMetadata(RULES_KEY, rule, target, propertyKey as string);
} else {
// class decorator
if (Joi.isSchema(rule)) {
// TODO 下一个大版本,metadata 这里要完全重构,临时先加一个后缀
// mix schema with property
// saveClassMetadata(RULES_CLASS_KEY + '_EXT', rule, target);
}
}
};
}
export { Joi as RuleType };