forked from brendon1982/ts-mocking-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07_use_it_all.ts
46 lines (38 loc) · 1.19 KB
/
07_use_it_all.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
import { Item } from '../dependencies/Item'
import { InMemoryCache } from '../dependencies/InMemoryCache'
import { ItemRepository } from '../dependencies/ItemRepository'
import { PubSub, PubSubChannels } from './06_PubSub'
export class ItemProcessor {
private pubSub: PubSub
private isProcessing: boolean = false
private processedItems: Item[] = []
constructor(
private cache: InMemoryCache,
private itemRepository: ItemRepository,
) {
this.pubSub = PubSub.getInstance()
}
async processItems(): Promise<void> {
if (this.isProcessing) {
return
}
this.isProcessing = true
const unprocessedItems = await this.getUnprocessedItems()
for (const item of unprocessedItems) {
this.cache.update(item)
this.pubSub.publish(PubSubChannels.itemUpdated, item)
this.processedItems.push(item)
}
this.isProcessing = false
this.processAgainAfterInterval()
}
private async getUnprocessedItems(): Promise<Item[]> {
const items = await this.itemRepository.getAll()
return items.filter((_) => !this.processedItems.includes(_))
}
private processAgainAfterInterval() {
setTimeout(() => {
this.processItems()
}, 5000)
}
}