-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entities.service.ts
37 lines (31 loc) · 1.02 KB
/
entities.service.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
import { Injectable } from '@nestjs/common';
import { Entity } from './entity.entity';
import { EntityProxyHandler } from './entity.proxy';
import { EntityOptions } from './entity-options.entity';
import { InjectEventEmitter } from 'nest-emitter';
import { EntitiesEventEmitter } from './entities.events';
@Injectable()
export class EntitiesService {
private readonly entities = new Map<string, Entity>();
constructor(
@InjectEventEmitter() private readonly emitter: EntitiesEventEmitter
) {}
has(id: string): boolean {
return this.entities.has(id);
}
get(id: string): Entity {
return this.entities.get(id);
}
add(entity: Entity, entityOptions?: EntityOptions): Entity {
if (this.entities.has(entity.id)) {
throw new Error(`Entity with id ${entity.id} already exists!`);
}
const proxy = new Proxy<Entity>(
entity,
new EntityProxyHandler(this.emitter)
);
this.entities.set(entity.id, proxy);
this.emitter.emit('newEntity', proxy, entityOptions);
return proxy;
}
}