/
prop.decorator.ts
44 lines (39 loc) 路 1.48 KB
/
prop.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
import * as mongoose from 'mongoose';
import { CannotDetermineTypeError } from '../errors';
import { RAW_OBJECT_DEFINITION } from '../mongoose.constants';
import { TypeMetadataStorage } from '../storages/type-metadata.storage';
const TYPE_METADATA_KEY = 'design:type';
/**
* Interface defining property options that can be passed to `@Prop()` decorator.
*/
export type PropOptions<T = any> =
| Partial<mongoose.SchemaDefinitionProperty<T>>
| mongoose.SchemaType;
/**
* @Prop decorator is used to mark a specific class property as a Mongoose property.
* Only properties decorated with this decorator will be defined in the schema.
*/
export function Prop(options?: PropOptions): PropertyDecorator {
return (target: object, propertyKey: string | symbol) => {
options = (options || {}) as mongoose.SchemaTypeOptions<unknown>;
const isRawDefinition = options[RAW_OBJECT_DEFINITION];
if (!options.type && !Array.isArray(options) && !isRawDefinition) {
const type = Reflect.getMetadata(TYPE_METADATA_KEY, target, propertyKey);
if (type === Array) {
options.type = [];
} else if (type && type !== Object) {
options.type = type;
} else {
throw new CannotDetermineTypeError(
target.constructor?.name,
propertyKey as string,
);
}
}
TypeMetadataStorage.addPropertyMetadata({
target: target.constructor,
propertyKey: propertyKey as string,
options: options as PropOptions,
});
};
}