forked from vendii-tech/simple-pubsub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
594 lines (533 loc) · 14.3 KB
/
app.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/**
* Custom error class for stock-related errors.
*/
export class StockError extends Error {
/**
* Constructs a new StockError instance.
* @param message - The error message.
*/
constructor(message: string) {
super(message);
this.name = "StockError";
}
}
/**
* Enum representing different types of machine events.
*/
export enum MachineEventType {
SALE = "SALE",
REFILL = "REFILL",
LOW_STOCK = "LOW_STOCK",
STOCK_OK = "STOCK_OK",
}
/**
* Threshold for low stock level.
*/
const STOCK_THRESHOLD = 3;
/**
* Interface representing an event.
*/
interface IEvent {
/**
* Gets the type of the event.
* @returns The event type.
*/
type(): MachineEventType;
/**
* Gets the ID of the machine associated with the event.
* @returns The machine ID.
*/
machineId(): string;
}
/**
* Interface representing a subscriber that handles events.
*/
interface ISubscriber {
/**
* Handles the given event.
* @param event - The event to handle.
*/
handle(event: IEvent): void;
}
/**
* Interface for a publish-subscribe service.
*/
interface IPublishSubscribeService {
/**
* Publishes an event to all subscribers.
* @param event - The event to publish.
*/
publish(event: IEvent): void;
/**
* Subscribes a handler to a specific event type.
* @param type - The event type to subscribe to.
* @param handler - The handler to subscribe.
*/
subscribe(type: MachineEventType, handler: ISubscriber): void;
/**
* Unsubscribes a handler from a specific event type.
* @param type - The event type to unsubscribe from.
* @param handler - The handler to unsubscribe.
*/
unsubscribe(type: MachineEventType, handler: ISubscriber): void;
}
/**
* Interface for a machine repository.
*/
export interface IMachineRepository {
/**
* Finds a machine by its ID.
* @param id - The ID of the machine.
* @returns The machine, or undefined if not found.
*/
findById(id: string): Machine | undefined;
/**
* Finds all machines.
* @returns An array of all machines.
*/
findAll(): Machine[];
/**
* Saves a new machine.
* @param machine - The machine to save.
*/
save(machine: Machine): void;
/**
* Updates an existing machine.
* @param machine - The machine to update.
*/
update(machine: Machine): void;
/**
* Deletes a machine by its ID.
* @param id - The ID of the machine to delete.
*/
delete(id: string): void;
}
/**
* Publish-subscribe service implementation.
*/
export class PubSubService implements IPublishSubscribeService {
private static instance: PubSubService;
private subscribers: Map<MachineEventType, ISubscriber[]> = new Map();
private constructor() {
this.publish = this.publish.bind(this);
this.subscribe = this.subscribe.bind(this);
this.unsubscribe = this.unsubscribe.bind(this);
}
/**
* Gets the singleton instance of the PubSubService.
* @returns The singleton instance.
*/
public static getInstance(): PubSubService {
if (!PubSubService.instance) {
PubSubService.instance = new PubSubService();
}
return PubSubService.instance;
}
/**
* Publishes an event to all subscribers.
* @param event - The event to publish.
*/
publish(event: IEvent): void {
const type = event.type();
const handlers = this.subscribers.get(type) || [];
if (handlers) {
handlers.map((handler) => handler.handle(event));
}
}
/**
* Subscribes a handler to a specific event type.
* @param type - The event type to subscribe to.
* @param handler - The handler to subscribe.
*/
subscribe(type: MachineEventType, handler: ISubscriber): void {
const handlers = this.subscribers.get(type) || [];
handlers.push(handler);
this.subscribers.set(type, handlers);
}
/**
* Unsubscribes a handler from a specific event type.
* @param type - The event type to unsubscribe from.
* @param handler - The handler to unsubscribe.
*/
unsubscribe(type: MachineEventType, handler: ISubscriber): void {
const handlers = this.subscribers.get(type) || [];
const newHandlers = handlers.filter((h) => h !== handler);
this.subscribers.set(type, newHandlers);
}
}
/**
* Machine repository implementation.
*/
export class MachineRepository implements IMachineRepository {
private machines: Map<string, Machine> = new Map();
/**
* Finds a machine by its ID.
* @param id - The ID of the machine.
* @returns The machine, or undefined if not found.
*/
findById(id: string): Machine | undefined {
return this.machines.get(id);
}
/**
* Finds all machines.
* @returns An array of all machines.
*/
findAll(): Machine[] {
return Array.from(this.machines.values());
}
/**
* Saves a new machine.
* @param machine - The machine to save.
*/
save(machine: Machine): void {
if (this.machines.has(machine.id)) {
throw new Error(`Machine with id ${machine.id} already exists`);
}
this.machines.set(machine.id, machine);
}
/**
* Updates an existing machine.
* @param machine - The machine to update.
*/
update(machine: Machine): void {
if (!this.machines.has(machine.id)) {
throw new Error(`Machine with id ${machine.id} not found`);
}
this.machines.set(machine.id, machine);
}
/**
* Deletes a machine by its ID.
* @param id - The ID of the machine to delete.
*/
delete(id: string): void {
if (!this.machines.delete(id)) {
throw new Error(`Machine with id ${id} not found`);
}
}
}
/**
* Event representing a machine sale.
*/
export class MachineSaleEvent implements IEvent {
/**
* Constructs a new MachineSaleEvent instance.
* @param _sold - The quantity sold.
* @param _machineId - The ID of the machine.
*/
constructor(
private readonly _sold: number,
private readonly _machineId: string
) {}
/**
* Gets the ID of the machine associated with the event.
* @returns The machine ID.
*/
machineId(): string {
return this._machineId;
}
/**
* Gets the quantity sold.
* @returns The quantity sold.
*/
getSoldQuantity(): number {
return this._sold;
}
/**
* Gets the type of the event.
* @returns The event type.
*/
type(): MachineEventType {
return MachineEventType.SALE;
}
/**
* Updates the stock level of the machine.
* @param machines - The list of machines.
*/
updateStock(machines: Machine[]): void {
const machine = machines.find((m) => m.id === this._machineId);
if (machine) {
let stockBefore = machine.stockLevel;
machine.stockLevel -= this._sold;
try {
if (machine.stockLevel < 0) {
throw new StockError("Stock level cannot be negative");
}
} catch (error: unknown) {
if (error instanceof StockError) {
console.error(error.message);
console.log("Rolling back stock level");
machine.stockLevel = stockBefore;
} else {
throw error;
}
}
if (machine.stockLevel < STOCK_THRESHOLD) {
const lowStockEvent = new LowStockWarningEvent(this._machineId);
PubSubService.getInstance().publish(lowStockEvent);
}
}
}
}
/**
* Event representing a machine refill.
*/
export class MachineRefillEvent implements IEvent {
/**
* Constructs a new MachineRefillEvent instance.
* @param _refill - The quantity refilled.
* @param _machineId - The ID of the machine.
*/
constructor(
private readonly _refill: number,
private readonly _machineId: string
) {}
/**
* Gets the ID of the machine associated with the event.
* @returns The machine ID.
*/
machineId(): string {
return this._machineId;
}
/**
* Gets the type of the event.
* @returns The event type.
*/
type(): MachineEventType {
return MachineEventType.REFILL;
}
/**
* Gets the quantity refilled.
* @returns The quantity refilled.
*/
getRefillQuantity(): number {
return this._refill;
}
/**
* Updates the stock level of the machine.
* @param machines - The list of machines.
*/
updateStock(machines: Machine[]): void {
const machine = machines.find((m) => m.id === this._machineId);
if (machine) {
let stockBefore = machine.stockLevel;
machine.stockLevel += this._refill;
if (
stockBefore < STOCK_THRESHOLD &&
machine.stockLevel >= STOCK_THRESHOLD
) {
const stockOKEvent = new StockOKEvent(this._machineId);
PubSubService.getInstance().publish(stockOKEvent);
}
}
}
}
/**
* Event representing a low stock warning.
*/
export class LowStockWarningEvent implements IEvent {
/**
* Constructs a new LowStockWarningEvent instance.
* @param _machineId - The ID of the machine.
*/
constructor(private readonly _machineId: string) {}
/**
* Gets the ID of the machine associated with the event.
* @returns The machine ID.
*/
machineId(): string {
return this._machineId;
}
/**
* Gets the type of the event.
* @returns The event type.
*/
type(): MachineEventType {
return MachineEventType.LOW_STOCK;
}
}
/**
* Event representing a stock OK notification.
*/
export class StockOKEvent implements IEvent {
/**
* Constructs a new StockOKEvent instance.
* @param _machineId - The ID of the machine.
*/
constructor(private readonly _machineId: string) {}
/**
* Gets the ID of the machine associated with the event.
* @returns The machine ID.
*/
machineId(): string {
return this._machineId;
}
/**
* Gets the type of the event.
* @returns The event type.
*/
type(): MachineEventType {
return MachineEventType.STOCK_OK;
}
}
/**
* Subscriber for machine sale events.
*/
export class MachineSaleSubscriber implements ISubscriber {
/**
* Constructs a new MachineSaleSubscriber instance.
* @param repository - The machine repository.
*/
constructor(private repository: IMachineRepository) {}
/**
* Handles a machine sale event.
* @param event - The machine sale event.
*/
handle(event: MachineSaleEvent): void {
const machine = this.repository.findById(event.machineId());
if (machine) {
let stockBefore = machine.stockLevel;
machine.stockLevel -= event.getSoldQuantity();
try {
if (machine.stockLevel < 0) {
throw new StockError("Stock level cannot be negative");
}
this.repository.update(machine);
} catch (error: unknown) {
if (error instanceof StockError) {
console.error(error.message);
console.log("Rolling back stock level");
machine.stockLevel = stockBefore;
this.repository.update(machine);
} else {
throw error;
}
}
if (machine.stockLevel < STOCK_THRESHOLD) {
const lowStockEvent = new LowStockWarningEvent(event.machineId());
PubSubService.getInstance().publish(lowStockEvent);
}
}
}
}
/**
* Subscriber for machine refill events.
*/
export class MachineRefillSubscriber implements ISubscriber {
/**
* Constructs a new MachineRefillSubscriber instance.
* @param repository - The machine repository.
*/
constructor(private repository: IMachineRepository) {}
/**
* Handles a machine refill event.
* @param event - The machine refill event.
*/
handle(event: MachineRefillEvent): void {
const machine = this.repository.findById(event.machineId());
if (machine) {
let stockBefore = machine.stockLevel;
machine.stockLevel += event.getRefillQuantity();
this.repository.update(machine);
if (
stockBefore < STOCK_THRESHOLD &&
machine.stockLevel >= STOCK_THRESHOLD
) {
const stockOKEvent = new StockOKEvent(event.machineId());
PubSubService.getInstance().publish(stockOKEvent);
}
}
}
}
/**
* Subscriber for low stock warning events.
*/
export class StockWarningSubscriber implements ISubscriber {
/**
* Constructs a new StockWarningSubscriber instance.
* @param repository - The machine repository.
*/
constructor(private repository: IMachineRepository) {}
/**
* Handles a low stock warning event.
* @param event - The low stock warning event.
*/
handle(event: LowStockWarningEvent): void {
console.log(`Low stock warning for machine ${event.machineId()}`);
}
}
/**
* Subscriber for stock OK events.
*/
export class StockOKSubscriber implements ISubscriber {
/**
* Constructs a new StockOKSubscriber instance.
* @param repository - The machine repository.
*/
constructor(private repository: IMachineRepository) {}
/**
* Handles a stock OK event.
* @param event - The stock OK event.
*/
handle(event: StockOKEvent): void {
console.log(`Stock OK for machine ${event.machineId()}`);
}
}
/**
* Represents a machine with a stock level.
*/
export class Machine {
public stockLevel = 10;
public id: string;
/**
* Constructs a new Machine instance.
* @param id - The ID of the machine.
*/
constructor(id: string) {
this.id = id;
}
}
/**
* Generates a random machine ID.
* @returns A random machine ID.
*/
const randomMachine = (): string => {
const random = Math.random() * 3;
if (random < 1) {
return "001";
} else if (random < 2) {
return "002";
}
return "003";
};
/**
* Generates a random event.
* @returns A random event.
*/
const eventGenerator = (): IEvent => {
const random = Math.random();
if (random < 0.5) {
const saleQty = Math.random() < 0.5 ? 1 : 2; // 1 or 2
return new MachineSaleEvent(saleQty, randomMachine());
}
const refillQty = Math.random() < 0.5 ? 3 : 5; // 3 or 5
return new MachineRefillEvent(refillQty, randomMachine());
};
/**
* Main program execution.
*/
(async () => {
// create 3 machines with a quantity of 10 stock
const machineRepository = new MachineRepository();
// save the machines
machineRepository.save(new Machine("001"));
machineRepository.save(new Machine("002"));
machineRepository.save(new Machine("003"));
// create a machine sale event subscriber. inject the machines (all subscribers should do this)
const saleSubscriber = new MachineSaleSubscriber(machineRepository);
// create the PubSub service
const pubSubService: IPublishSubscribeService = PubSubService.getInstance();
// create 5 random events
const events = [1, 2, 3, 4, 5].map((i) => eventGenerator());
// publish the events
events.map(pubSubService.publish);
})();