-
Notifications
You must be signed in to change notification settings - Fork 353
Expand file tree
/
Copy pathmtimeCorrelatedCache.ts
More file actions
76 lines (66 loc) · 1.95 KB
/
mtimeCorrelatedCache.ts
File metadata and controls
76 lines (66 loc) · 1.95 KB
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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import { mkdirSync } from 'fs';
import { dirname } from 'path';
import { IDisposable } from '../disposable';
import { readfile, writeFile } from '../fsUtils';
import { debounce } from '../objUtils';
export class CorrelatedCache<C, V> implements IDisposable {
private cacheData?: Promise<{ [key: string]: { correlation: C; value: V } }>;
/**
* Scheules the cache to flush to disk.
*/
public readonly flush = debounce(this.debounceTime, () => this.flushImmediately());
constructor(private readonly storageFile: string, private readonly debounceTime = 500) {
try {
mkdirSync(dirname(storageFile));
} catch {
// ignored
}
}
/**
* Gets the value from the map if it exists and the correlation matches.
*/
public async lookup(key: string, correlation?: C): Promise<V | undefined> {
const data = await this.getData();
const entry = data[key];
return entry && (correlation === undefined || entry.correlation === correlation)
? entry.value
: undefined;
}
/**
* Stores the value in the cache.
*/
public async store(key: string, correlation: C, value: V) {
const data = await this.getData();
data[key] = { correlation, value };
this.flush();
}
/**
* Flushes the cache to disk immediately.
*/
public async flushImmediately() {
this.flush.clear();
return writeFile(this.storageFile, JSON.stringify(await this.getData()));
}
/**
* @inheritdoc
*/
public dispose() {
this.flushImmediately();
}
private getData() {
if (!this.cacheData) {
this.cacheData = this.hydrateFromDisk();
}
return this.cacheData;
}
private async hydrateFromDisk() {
try {
return JSON.parse(await readfile(this.storageFile)) || {};
} catch (e) {
return {};
}
}
}