Skip to content

Commit 5825134

Browse files
committed
Implement event emitter integration in AbstractServiceSchema and AbstractIdentitiesService
1 parent 633b4a7 commit 5825134

File tree

3 files changed

+56
-14
lines changed

3 files changed

+56
-14
lines changed

src/_common/abstracts/abstract.service.schema.ts

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,34 @@ export abstract class AbstractServiceSchema extends AbstractService implements S
3737
projection?: ProjectionType<T> | null | undefined,
3838
options?: QueryOptions<T> | null | undefined,
3939
): Promise<Query<Array<T>, T, any, T>[]> {
40-
//TODO: add event emitter
40+
if (this.eventEmitter) {
41+
const beforeEvents = await this.eventEmitter?.emitAsync(
42+
[this.moduleName.toLowerCase(), this.serviceName.toLowerCase(), 'service', 'beforeFind'].join(EventEmitterSeparator),
43+
{ filter, projection, options },
44+
)
45+
for (const beforeEvent of beforeEvents) {
46+
if (beforeEvent?.stop) throw beforeEvent?.stop
47+
if (beforeEvent?.filter) filter = { ...filter, ...beforeEvent.filter }
48+
if (beforeEvent?.projection) projection = { ...(typeof projection === 'object' ? projection : {}), ...beforeEvent.projection }
49+
if (beforeEvent?.options) options = { ...options, ...beforeEvent.options }
50+
}
51+
}
4152
this.logger.debug(['find', JSON.stringify(Object.values(arguments))].join(' '))
4253
return await this._model.find<Query<Array<T>, T, any, T>>(filter, projection, options).exec()
4354
}
4455

4556
public async count<T extends AbstractSchema | Document>(filter?: FilterQuery<T>, options?: (mongodb.CountOptions & MongooseBaseQueryOptions<T>) | null): Promise<number> {
46-
//TODO: add event emitter
57+
if (this.eventEmitter) {
58+
const beforeEvents = await this.eventEmitter?.emitAsync(
59+
[this.moduleName.toLowerCase(), this.serviceName.toLowerCase(), 'service', 'beforeCount'].join(EventEmitterSeparator),
60+
{ filter, options },
61+
)
62+
for (const beforeEvent of beforeEvents) {
63+
if (beforeEvent?.stop) throw beforeEvent?.stop
64+
if (beforeEvent?.filter) filter = { ...filter, ...beforeEvent.filter }
65+
if (beforeEvent?.options) options = { ...options, ...beforeEvent.options }
66+
}
67+
}
4768
this.logger.debug(['count', JSON.stringify(Object.values(arguments))].join(' '))
4869
return await this._model.countDocuments(filter, options).exec()
4970
}
@@ -64,11 +85,11 @@ export abstract class AbstractServiceSchema extends AbstractService implements S
6485
): Promise<[Array<T & Query<T, T, any, T>>, number]> {
6586
this.logger.debug(['findAndCount', JSON.stringify(Object.values(arguments))].join(' '))
6687
if (this.eventEmitter) {
88+
console.log('de', [this.moduleName.toLowerCase(), this.serviceName.toLowerCase(), 'service', 'beforeFindAndCount'].join(EventEmitterSeparator))
6789
const beforeEvents = await this.eventEmitter?.emitAsync(
6890
[this.moduleName.toLowerCase(), this.serviceName.toLowerCase(), 'service', 'beforeFindAndCount'].join(EventEmitterSeparator),
6991
{ filter, projection, options },
7092
)
71-
// noinspection DuplicatedCode
7293
for (const beforeEvent of beforeEvents) {
7394
if (beforeEvent?.stop) throw beforeEvent?.stop
7495
if (beforeEvent?.filter) filter = { ...filter, ...beforeEvent.filter }
@@ -80,6 +101,7 @@ export abstract class AbstractServiceSchema extends AbstractService implements S
80101
filter = { ...filter, ...softDelete }
81102
let count = await this._model.countDocuments(filter).exec()
82103
let data = await this._model.find<T & Query<T, T, any, T>>(filter, projection, options).exec()
104+
83105
if (this.eventEmitter) {
84106
const afterEvents = await this.eventEmitter?.emitAsync(
85107
[this.moduleName.toLowerCase(), this.serviceName.toLowerCase(), 'service', 'afterFindAndCount'].join(EventEmitterSeparator),
@@ -90,6 +112,7 @@ export abstract class AbstractServiceSchema extends AbstractService implements S
90112
if (afterEvent?.count) count += afterEvent.count
91113
}
92114
}
115+
93116
return [data, count]
94117
}
95118

@@ -99,6 +122,7 @@ export abstract class AbstractServiceSchema extends AbstractService implements S
99122
options?: QueryOptions<T> | null | undefined,
100123
): Promise<Query<T, T, any, T>> {
101124
this.logger.debug(['findById', JSON.stringify(Object.values(arguments))].join(' '))
125+
102126
if (this.eventEmitter) {
103127
const beforeEvents = await this.eventEmitter?.emitAsync(
104128
[this.moduleName.toLowerCase(), this.serviceName.toLowerCase(), 'service', 'beforeFindById'].join(EventEmitterSeparator),
@@ -110,7 +134,9 @@ export abstract class AbstractServiceSchema extends AbstractService implements S
110134
if (beforeEvent?.options) options = { ...options, ...beforeEvent.options }
111135
}
112136
}
137+
113138
let data = await this._model.findById<Query<T | null, T, any, T>>(_id, projection, options).exec()
139+
114140
if (this.eventEmitter) {
115141
const afterEvents = await this.eventEmitter?.emitAsync(
116142
[this.moduleName.toLowerCase(), this.serviceName.toLowerCase(), 'service', 'afterFindById'].join(EventEmitterSeparator),
@@ -120,6 +146,7 @@ export abstract class AbstractServiceSchema extends AbstractService implements S
120146
if (afterEvent?.data) data = { ...data, ...afterEvent.data }
121147
}
122148
}
149+
123150
if (!data) {
124151
this.logger.debug(['findById', JSON.stringify(Object.values(arguments))].join(' '))
125152
throw new NotFoundException()

src/_common/abstracts/abstract.service.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ export interface AbstractServiceContext {
1010
moduleRef?: ModuleRef;
1111
req?: Request & { user?: Express.User };
1212
eventEmitter?: EventEmitter2;
13+
serviceName?: string;
14+
moduleName?: string;
1315
}
1416

1517
@Injectable()
@@ -19,16 +21,23 @@ export abstract class AbstractService {
1921
private readonly _req?: Request & { user?: Express.User & any } // eslint-disable-line
2022
protected eventEmitter?: EventEmitter2;
2123

24+
private _customServiceName: string;
25+
private _customModuleName: string;
26+
2227
protected constructor(context?: AbstractServiceContext) {
2328
this.moduleRef = context?.moduleRef;
2429
this._req = context?.req;
2530
this.logger = new Logger(this.serviceName);
31+
this.eventEmitter = context?.eventEmitter;
32+
33+
this._customModuleName = context?.moduleName
34+
this._customServiceName = context?.serviceName
2635
}
2736

2837
protected get request():
2938
| (Request & {
30-
user?: Express.User & any // eslint-disable-line
31-
})
39+
user?: Express.User & any // eslint-disable-line
40+
})
3241
| null {
3342
return this._req || RequestContext.currentContext?.req;
3443
}
@@ -37,10 +46,11 @@ export abstract class AbstractService {
3746
//TODO: change modulename from module ref ?
3847
if (!this.request) throw new Error('Request is not defined in ' + this.constructor.name);
3948
const moduleName = this.request.path.split('/').slice(1).shift();
40-
return moduleName.charAt(0).toUpperCase() + moduleName.slice(1);
49+
return this._customModuleName || moduleName.charAt(0).toUpperCase() + moduleName.slice(1);
4150
}
4251

4352
public get serviceName(): string {
44-
return this.constructor.name.replace(/Service$/, '');
53+
if (!this.constructor.name) throw new Error('Service name is not defined in ' + this.constructor.name);
54+
return this._customServiceName || this.constructor.name.replace(/Service$/, '');
4555
}
4656
}

src/management/identities/abstract-identities.service.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { PasswdadmService } from "~/settings/passwdadm.service";
1717
import { DataStatusEnum } from "~/management/identities/_enums/data-status";
1818
import { JobState } from "~/core/jobs/_enums/state.enum";
1919
import { inetOrgPersonDto } from './_dto/_parts/inetOrgPerson.dto';
20+
import { EventEmitter2 } from '@nestjs/event-emitter';
2021

2122
@Injectable()
2223
export abstract class AbstractIdentitiesService extends AbstractServiceSchema {
@@ -25,9 +26,13 @@ export abstract class AbstractIdentitiesService extends AbstractServiceSchema {
2526
protected readonly _validation: IdentitiesValidationService,
2627
protected readonly storage: FactorydriveService,
2728
protected readonly passwdAdmService: PasswdadmService,
29+
protected readonly eventEmitter: EventEmitter2,
2830
@Inject(forwardRef(() => BackendsService)) protected readonly backends: BackendsService,
2931
) {
30-
super();
32+
super({
33+
eventEmitter,
34+
serviceName: 'identities',
35+
});
3136
}
3237

3338
protected handleValidationError(
@@ -217,11 +222,11 @@ export abstract class AbstractIdentitiesService extends AbstractServiceSchema {
217222
let dataDup = [];
218223
if (data.inetOrgPerson.hasOwnProperty('mail') && data.inetOrgPerson.mail !== '') {
219224
const id = new Types.ObjectId(data['_id']);
220-
const f: any = { '_id': { $ne: id },'deletedFlag':{$ne:true}, $or: [{ 'inetOrgPerson.uid': data.inetOrgPerson.uid }, { 'inetOrgPerson.mail': data.inetOrgPerson.mail }] };
225+
const f: any = { '_id': { $ne: id }, 'deletedFlag': { $ne: true }, $or: [{ 'inetOrgPerson.uid': data.inetOrgPerson.uid }, { 'inetOrgPerson.mail': data.inetOrgPerson.mail }] };
221226
dataDup = await this._model.find(f).exec()
222227
} else {
223228
const id = new Types.ObjectId(data['_id']);
224-
const f: any = { '_id': { $ne: id },'deletedFlag':{$ne:true}, 'inetOrgPerson.uid': data.inetOrgPerson.uid };
229+
const f: any = { '_id': { $ne: id }, 'deletedFlag': { $ne: true }, 'inetOrgPerson.uid': data.inetOrgPerson.uid };
225230
dataDup = await this._model.find(f).exec()
226231
}
227232
if (dataDup.length > 0) {
@@ -234,8 +239,8 @@ export abstract class AbstractIdentitiesService extends AbstractServiceSchema {
234239
protected async checkMail(identity, data): Promise<boolean> {
235240
let dataDup = 0;
236241
if (data.inetOrgPerson.hasOwnProperty('mail') && data.inetOrgPerson.mail !== '') {
237-
if (identity){
238-
const f: any = { '_id': { $ne: identity._id },'state':{$ne:IdentityState.DONT_SYNC},'deletedFlag':{$ne:true}, 'inetOrgPerson.mail': identity.inetOrgPerson.mail };
242+
if (identity) {
243+
const f: any = { '_id': { $ne: identity._id }, 'state': { $ne: IdentityState.DONT_SYNC }, 'deletedFlag': { $ne: true }, 'inetOrgPerson.mail': identity.inetOrgPerson.mail };
239244
dataDup = await this._model.countDocuments(f).exec()
240245
} else {
241246
const f: any = { 'inetOrgPerson.mail': data.inetOrgPerson.mail };
@@ -252,8 +257,8 @@ export abstract class AbstractIdentitiesService extends AbstractServiceSchema {
252257

253258
protected async checkUid(identity, data): Promise<boolean> {
254259
let dataDup = 0;
255-
if (identity){
256-
const f: any = { '_id': { $ne: identity._id } ,'state':{$ne:IdentityState.DONT_SYNC},'deletedFlag':{$ne:true},'inetOrgPerson.uid': identity.inetOrgPerson.uid };
260+
if (identity) {
261+
const f: any = { '_id': { $ne: identity._id }, 'state': { $ne: IdentityState.DONT_SYNC }, 'deletedFlag': { $ne: true }, 'inetOrgPerson.uid': identity.inetOrgPerson.uid };
257262
dataDup = await this._model.countDocuments(f).exec()
258263
} else {
259264
const f: any = { 'inetOrgPerson.uid': data.inetOrgPerson.uid };

0 commit comments

Comments
 (0)