-
Notifications
You must be signed in to change notification settings - Fork 568
/
api-property.decorator.ts
77 lines (66 loc) 路 1.8 KB
/
api-property.decorator.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
67
68
69
70
71
72
73
74
75
76
77
import { DECORATORS } from '../constants';
import { SchemaObjectMetadata } from '../interfaces';
import { getEnumType, getEnumValues } from '../common/enum.utils';
import { createPropertyDecorator, getTypeIsArrayTuple } from './helpers';
export interface ApiPropertyOptions
extends Omit<SchemaObjectMetadata, 'name' | 'enum'> {
name?: string;
enum?: any[] | Record<string, any>;
enumName?: string;
$ref?: string;
}
const isEnumArray = (obj: ApiPropertyOptions): boolean =>
obj.isArray && !!obj.enum;
export function ApiProperty(
options: ApiPropertyOptions = {}
): PropertyDecorator {
return createApiPropertyDecorator(options);
}
export function createApiPropertyDecorator(
options: ApiPropertyOptions = {}
): PropertyDecorator {
const [type, isArray] = getTypeIsArrayTuple(options.type, options.isArray);
options = {
...options,
type,
};
if (isEnumArray(options)) {
options.type = 'array';
const enumValues = getEnumValues(options.enum);
options.items = {
type: getEnumType(enumValues),
enum: enumValues,
};
delete options.enum;
} else if (options.enum) {
const enumValues = getEnumValues(options.enum);
options.enum = enumValues;
options.type = getEnumType(enumValues);
}
if (isArray) {
options.type = 'array';
options.items = {
type: type as any,
};
}
return createPropertyDecorator(DECORATORS.API_MODEL_PROPERTIES, options);
}
export function ApiPropertyOptional(
options: ApiPropertyOptions = {}
): PropertyDecorator {
return ApiProperty({
...options,
required: false,
});
}
export function ApiResponseProperty(
options: Pick<
ApiPropertyOptions,
'type' | 'example' | 'format' | 'enum' | 'deprecated'
> = {}
): PropertyDecorator {
return ApiProperty({
readOnly: true,
...options,
});
}