-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathexpress-cassandra.providers.ts
49 lines (44 loc) · 1.58 KB
/
express-cassandra.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
import {
getModelToken,
getConnectionToken,
getRepositoryToken,
} from './utils/cassandra-orm.utils';
import { defer } from 'rxjs';
import { loadModel, Repository, ConnectionOptions, Connection } from './orm';
import { getEntity } from './orm/utils/decorator.utils';
import { Provider } from '@nestjs/common';
import { RepositoryFactory } from './orm/repositories/repository.factory';
export function createExpressCassandraProviders(
entities?: Function[],
connection?: Connection | ConnectionOptions | string,
) {
const providerModel = entity => ({
provide: getModelToken(entity),
useFactory: async (connectionLike: Connection) => {
return await defer(() => loadModel(connectionLike, entity)).toPromise();
},
inject: [getConnectionToken(connection)],
});
const provideRepository = entity => ({
provide: getRepositoryToken(entity),
useFactory: async model => RepositoryFactory.create(entity, model),
inject: [getModelToken(entity)],
});
const provideCustomRepository = EntityRepository => {
const entity = getEntity(EntityRepository);
return {
provide: getRepositoryToken(EntityRepository),
useFactory: async model =>
RepositoryFactory.create(entity, model, EntityRepository),
inject: [getModelToken(entity)],
};
};
const providers: Provider[] = [];
(entities || []).forEach(entity => {
if (entity.prototype instanceof Repository) {
return providers.push(provideCustomRepository(entity));
}
return providers.push(providerModel(entity), provideRepository(entity));
});
return [...providers];
}