-
-
Notifications
You must be signed in to change notification settings - Fork 286
/
schemaOptions.ts
61 lines (52 loc) · 1.56 KB
/
schemaOptions.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
import {deepExtends, Store} from "@tsed/core";
import {HookDoneFunction, HookNextFunction, Schema} from "mongoose";
import {MONGOOSE_SCHEMA_OPTIONS} from "../constants";
import {MongooseSchemaOptions} from "../interfaces";
/**
*
* @param target
* @param {MongooseSchemaOptions} options
*/
export function schemaOptions(target: any, options?: MongooseSchemaOptions) {
const store = Store.from(target);
if (!store.has(MONGOOSE_SCHEMA_OPTIONS)) {
store.set(MONGOOSE_SCHEMA_OPTIONS, {});
}
if (options) {
store.set(MONGOOSE_SCHEMA_OPTIONS, deepExtends(store.get(MONGOOSE_SCHEMA_OPTIONS), options));
}
return store.get(MONGOOSE_SCHEMA_OPTIONS);
}
/**
*
* @param {Function} fn
* @returns {any}
*/
export function buildPreHook(fn: Function) {
return fn.length === 2
? function(next: HookNextFunction) {
return fn(this, next);
}
: function(next: HookNextFunction, done: HookDoneFunction) {
return fn(this, next, done);
};
}
/**
*
* @param schema
* @param {MongooseSchemaOptions} options
*/
export function applySchemaOptions(schema: Schema, options: MongooseSchemaOptions) {
if (options.plugins) {
options.plugins.forEach(item => schema.plugin(item.plugin, item.options));
}
if (options.indexes) {
options.indexes.forEach(item => schema.index(item.fields, item.options));
}
if (options.pre) {
options.pre.forEach(item => schema.pre(item.method, !!item.parallel, buildPreHook(item.fn), item.errorCb));
}
if (options.post) {
options.post.forEach(item => schema.post(item.method, item.fn as any));
}
}