-
-
Notifications
You must be signed in to change notification settings - Fork 286
/
preHook.ts
79 lines (76 loc) · 1.84 KB
/
preHook.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
78
79
import {getDecoratorType} from "@tsed/core";
import {HookErrorCallback} from "mongoose";
import {MongoosePostErrorHookCB, MongoosePostHookCB, MongoosePreHookAsyncCB, MongoosePreHookSyncCB} from "../interfaces";
import {schemaOptions} from "../utils/schemaOptions";
export interface PreHookOptions {
parallel?: boolean;
errorCb?: HookErrorCallback;
}
/**
*
* We can simply attach a `@PreHook` decorator to your model class and
* define the hook function like you normally would in Mongoose.
*
* ```typescript
* import {Ignore, Required} from "@tsed/common";
* import {PreHook, Model} from "@tsed/mongoose";
*
* @Model()
* @PreHook("save", (car: CarModel, next) => {
* if (car.model === 'Tesla') {
* car.isFast = true;
* }
* next();
*})
* export class CarModel {
*
* @Ignore()
* _id: string;
*
* @Required()
* model: string;
*
* @Required()
* isFast: boolean;
*
* // or Prehook on static method
* @PreHook("save")
* static preSave(car: CarModel, next) {
* if (car.model === 'Tesla') {
* car.isFast = true;
* }
* next();
* }
* }
* ```
*
* This will execute the pre-save hook each time a `CarModel` document is saved.
*
* @param {string} method
* @param fn
* @param options
* @returns {Function}
* @decorator
* @class
*/
export function PreHook(
method: string,
fn?: MongoosePreHookSyncCB<any> | MongoosePreHookAsyncCB<any> | PreHookOptions,
options?: PreHookOptions
): Function {
return (...args: any[]) => {
if (getDecoratorType(args) === "method") {
options = fn as PreHookOptions;
fn = args[0][args[1]].bind(args[0]);
}
schemaOptions(args[0], {
pre: [
{
...(options || {}),
method,
fn: fn as MongoosePostHookCB<any> | MongoosePostErrorHookCB<any>
}
]
});
};
}