-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathmongoose.providers.ts
62 lines (60 loc) · 2.11 KB
/
mongoose.providers.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
import { Provider } from '@nestjs/common';
import { Connection, Document, Model } from 'mongoose';
import { getConnectionToken, getModelToken } from './common/mongoose.utils';
import { AsyncModelFactory, ModelDefinition } from './interfaces';
export function createMongooseProviders(
connectionName?: string,
options: ModelDefinition[] = [],
): Provider[] {
return options.reduce(
(providers, option) => [
...providers,
...(option.discriminators || []).map((d) => ({
provide: getModelToken(d.name, connectionName),
useFactory: (model: Model<Document>) =>
model.discriminator(d.name, d.schema, d.value),
inject: [getModelToken(option.name, connectionName)],
})),
{
provide: getModelToken(option.name, connectionName),
useFactory: (connection: Connection) => {
const model = connection.models[option.name]
? connection.models[option.name]
: connection.model(option.name, option.schema, option.collection);
return model;
},
inject: [getConnectionToken(connectionName)],
},
],
[] as Provider[],
);
}
export function createMongooseAsyncProviders(
connectionName?: string,
modelFactories: AsyncModelFactory[] = [],
): Provider[] {
return modelFactories.reduce((providers, option) => {
return [
...providers,
{
provide: getModelToken(option.name, connectionName),
useFactory: async (connection: Connection, ...args: unknown[]) => {
const schema = await option.useFactory(...args);
const model = connection.model(
option.name,
schema,
option.collection,
);
return model;
},
inject: [getConnectionToken(connectionName), ...(option.inject || [])],
},
...(option.discriminators || []).map((d) => ({
provide: getModelToken(d.name, connectionName),
useFactory: (model: Model<Document>) =>
model.discriminator(d.name, d.schema, d.value),
inject: [getModelToken(option.name, connectionName)],
})),
];
}, [] as Provider[]);
}