-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
typegoose.ts
195 lines (171 loc) · 5.84 KB
/
typegoose.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
/* imports */
import * as mongoose from 'mongoose';
import 'reflect-metadata';
import { isNullOrUndefined } from 'util';
import { constructors, hooks, methods, models, plugins, schema, virtuals } from './data';
/* exports */
export * from './method';
export * from './prop';
export * from './hooks';
export * from './plugin';
export * from '.';
export * from './typeguards';
export { getClassForDocument } from './utils';
export type DocumentType<T> = T & mongoose.Document;
export type ModelType<T> = mongoose.Model<DocumentType<T>> & T;
export interface GetModelForClassOptions {
/** An Existing Mongoose Connection */
existingMongoose?: mongoose.Mongoose;
/** Supports all Mongoose's Schema Options */
schemaOptions?: mongoose.SchemaOptions;
/** An Existing Connection */
existingConnection?: mongoose.Connection;
}
/**
* Main Class
*/
export class Typegoose {
/**
* Get a Model for a Class
* Executes .setModelForClass if it cant find it already
* @param t The uninitialized Class
* @param __namedParameters The Options
* @param existingMongoose An Existing Mongoose Connection
* @param schemaOptions Supports all Mongoose's Schema Options
* @param existingConnection An Existing Connection
* @returns The Model
* @public
*/
public getModelForClass<T>(
t: T,
{ existingMongoose, schemaOptions, existingConnection }: GetModelForClassOptions = {}
) {
const name = this.constructor.name;
if (!models[name]) {
this.setModelForClass(t, {
existingMongoose,
schemaOptions,
existingConnection,
});
}
return models[name] as ModelType<this> & T;
}
/**
* Builds the Schema & The Model
* @param t The uninitialized Class
* @param __namedParameters The Options
* @param existingMongoose An Existing Mongoose Connection
* @param schemaOptions Supports all Mongoose's Schema Options
* @param existingConnection An Existing Connection
* @returns The Model
* @public
*/
public setModelForClass<T>(
t: T,
{ existingMongoose, schemaOptions, existingConnection }: GetModelForClassOptions = {}
) {
const name = this.constructor.name;
const sch = this.buildSchema<T>(t, { existingMongoose, schemaOptions });
let model = mongoose.model.bind(mongoose);
if (existingConnection) {
model = existingConnection.model.bind(existingConnection);
} else if (existingMongoose) {
model = existingMongoose.model.bind(existingMongoose);
}
models[name] = model(name, sch);
constructors[name] = this.constructor;
return models[name] as ModelType<this> & T;
}
/**
* Generates a Mongoose schema out of class props, iterating through all parents
* @param t The not initialized Class
* @param schemaOptions Options for the Schema
* @returns Returns the Build Schema
*/
public buildSchema<T>(t: T, { schemaOptions }: GetModelForClassOptions = {}) {
const name = this.constructor.name;
// get schema of current model
let sch = _buildSchema<T>(t, name, schemaOptions);
/** Parent Constructor */
let parentCtor = Object.getPrototypeOf(this.constructor.prototype).constructor;
// iterate trough all parents
while (parentCtor && parentCtor.name !== 'Typegoose' && parentCtor.name !== 'Object') {
// extend schema
sch = _buildSchema<T>(t, parentCtor.name, schemaOptions, sch);
// next parent
parentCtor = Object.getPrototypeOf(parentCtor.prototype).constructor;
}
return sch;
}
}
/**
* Private schema builder out of class props
* -> If you discover this, dont use this function, use Typegoose.buildSchema!
* @param t The not initialized Class
* @param name The Name to save the Schema Under (Mostly Constructor.name)
* @param schemaOptions Options for the Schema
* @param sch Already Existing Schema?
* @returns Returns the Build Schema
* @private
*/
function _buildSchema<T>(t: T, name: string, schemaOptions: any, sch?: mongoose.Schema) {
/** Simplify the usage */
const Schema = mongoose.Schema;
if (!sch) {
sch = schemaOptions ? new Schema(schema[name], schemaOptions) : new Schema(schema[name]);
} else {
sch.add(schema[name]);
}
/** Simplify the usage */
const staticMethods = methods.staticMethods[name];
if (staticMethods) {
sch.statics = Object.assign(staticMethods, sch.statics || {});
} else {
sch.statics = sch.statics || {};
}
/** Simplify the usage */
const instanceMethods = methods.instanceMethods[name];
if (instanceMethods) {
sch.methods = Object.assign(instanceMethods, sch.methods || {});
} else {
sch.methods = sch.methods || {};
}
const hook = hooks.get(name);
if (hook) {
hook.pre.forEach((v, k) => {
if (!isNullOrUndefined(v.parallel)) {
sch.pre(k, v.parallel, v.func);
} else {
sch.pre(k as string, v.func); // look at https://github.com/DefinitelyTyped/DefinitelyTyped/issues/37333
}
});
hook.post.forEach((v, k) => sch.post(k, v.func));
}
if (plugins[name]) { // same as the "if (hooks[name])"
for (const plugin of plugins[name]) {
sch.plugin(plugin.mongoosePlugin, plugin.options);
}
}
/** Simplify the usage */
const getterSetters = virtuals[name];
if (getterSetters) {
for (const key of Object.keys(getterSetters)) {
if (getterSetters[key].options && getterSetters[key].options.overwrite) {
sch.virtual(key, getterSetters[key].options);
} else {
if (getterSetters[key].get) {
sch.virtual(key, getterSetters[key].options).get(getterSetters[key].get);
}
if (getterSetters[key].set) {
sch.virtual(key, getterSetters[key].options).set(getterSetters[key].set);
}
}
}
}
/** Get Metadata for indices */
const indices = Reflect.getMetadata('typegoose:indices', t) || [];
for (const index of indices) {
sch.index(index.fields, index.options);
}
return sch;
}