-
Notifications
You must be signed in to change notification settings - Fork 0
/
orm-decorators.ts
56 lines (43 loc) · 1.95 KB
/
orm-decorators.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
import * as Joi from "@hapi/joi";
import {OrmGlobalHelpers} from "./orm-global-helpers";
import {ObjectId} from "bson";
export type OrmDocumentClass = {
new(...args: any[]): { _id: any };
databaseName: string;
collectionName: string;
};
export type OrmDocumentInstance = InstanceType<OrmDocumentClass>;
export function Document<T extends OrmDocumentClass>(classConstructor: T) {
OrmGlobalHelpers.Models.add(classConstructor);
return classConstructor;
}
export function Field(joiSchema: Joi.Schema) {
return function(target: InstanceType<OrmDocumentClass>, propertyKey: string) {
let modelConstructor = target.constructor as OrmDocumentClass;
if (!OrmGlobalHelpers.Validators.has(modelConstructor)) {
OrmGlobalHelpers.Validators.set(modelConstructor, {});
}
if (!OrmGlobalHelpers.Fields.has(modelConstructor)) {
OrmGlobalHelpers.Fields.set(modelConstructor, []);
}
let validatorsForTarget = OrmGlobalHelpers.Validators.get(modelConstructor) as Joi.SchemaMap;
validatorsForTarget[propertyKey] = joiSchema;
let fieldsForTarget = OrmGlobalHelpers.Fields.get(modelConstructor) as string[];
fieldsForTarget.push(propertyKey);
}
}
export function ObjectIdField() {
return function(target: InstanceType<OrmDocumentClass>, propertyKey: string) {
let modelConstructor = target.constructor as OrmDocumentClass;
if (!OrmGlobalHelpers.Validators.has(modelConstructor)) {
OrmGlobalHelpers.Validators.set(modelConstructor, {});
}
if (!OrmGlobalHelpers.Fields.has(modelConstructor)) {
OrmGlobalHelpers.Fields.set(modelConstructor, []);
}
let validatorsForTarget = OrmGlobalHelpers.Validators.get(modelConstructor) as Joi.SchemaMap;
validatorsForTarget[propertyKey] = Joi.object().type(ObjectId).required();
let fieldsForTarget = OrmGlobalHelpers.Fields.get(modelConstructor) as string[];
fieldsForTarget.push(propertyKey);
}
}