-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entities.service.ts
74 lines (66 loc) · 2.03 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
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
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
import { Entity } from './entity';
import { EntityProxyHandler } from './entity.proxy';
import { InjectEventEmitter } from 'nest-emitter';
import { EntitiesEventEmitter } from './entities.events';
import { EntityCustomization } from './entity-customization.interface';
import { ClusterService } from '../cluster/cluster.service';
@Injectable()
export class EntitiesService implements OnApplicationBootstrap {
private readonly entities: Map<string, Entity> = new Map<string, Entity>();
private readonly logger: Logger;
constructor(
private readonly clusterService: ClusterService,
@InjectEventEmitter() private readonly emitter: EntitiesEventEmitter
) {
this.logger = new Logger(EntitiesService.name);
}
onApplicationBootstrap(): void {
this.clusterService.on('elected', () => {
this.refreshStates();
});
}
has(id: string): boolean {
return this.entities.has(id);
}
get(id: string): Entity {
return this.entities.get(id);
}
add(
entity: Entity,
customizations?: Array<EntityCustomization<any>>
): 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.clusterService.isMajorityLeader.bind(this.clusterService)
)
);
this.entities.set(entity.id, proxy);
this.emitter.emit('newEntity', proxy, customizations);
return proxy;
}
refreshStates(): void {
this.logger.log('Refreshing entity states');
this.entities.forEach(entity => {
if (!entity.distributed || this.clusterService.isMajorityLeader()) {
this.emitter.emit(
'stateUpdate',
entity.id,
entity.state,
entity.distributed
);
this.emitter.emit(
'attributesUpdate',
entity.id,
entity.attributes,
entity.distributed
);
}
});
}
}