diff options
Diffstat (limited to 'server/models/model-cache.ts')
-rw-r--r-- | server/models/model-cache.ts | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/server/models/model-cache.ts b/server/models/model-cache.ts new file mode 100644 index 000000000..bfa163b6b --- /dev/null +++ b/server/models/model-cache.ts | |||
@@ -0,0 +1,54 @@ | |||
1 | import { Model } from 'sequelize-typescript' | ||
2 | import * as Bluebird from 'bluebird' | ||
3 | import { logger } from '@server/helpers/logger' | ||
4 | |||
5 | type ModelCacheType = | ||
6 | 'local-account-name' | ||
7 | | 'local-actor-name' | ||
8 | | 'local-actor-url' | ||
9 | |||
10 | class ModelCache { | ||
11 | |||
12 | private static instance: ModelCache | ||
13 | |||
14 | private readonly localCache: { [id in ModelCacheType]: Map<string, any> } = { | ||
15 | 'local-account-name': new Map(), | ||
16 | 'local-actor-name': new Map(), | ||
17 | 'local-actor-url': new Map() | ||
18 | } | ||
19 | |||
20 | private constructor () { | ||
21 | } | ||
22 | |||
23 | static get Instance () { | ||
24 | return this.instance || (this.instance = new this()) | ||
25 | } | ||
26 | |||
27 | doCache<T extends Model> (options: { | ||
28 | cacheType: ModelCacheType | ||
29 | key: string | ||
30 | fun: () => Bluebird<T> | ||
31 | whitelist?: () => boolean | ||
32 | }) { | ||
33 | const { cacheType, key, fun, whitelist } = options | ||
34 | |||
35 | if (whitelist && whitelist() !== true) return fun() | ||
36 | |||
37 | const cache = this.localCache[cacheType] | ||
38 | |||
39 | if (cache.has(key)) { | ||
40 | logger.debug('Model cache hit for %s -> %s.', cacheType, key) | ||
41 | return Bluebird.resolve<T>(cache.get(key)) | ||
42 | } | ||
43 | |||
44 | return fun().then(m => { | ||
45 | if (!whitelist || whitelist()) cache.set(key, m) | ||
46 | |||
47 | return m | ||
48 | }) | ||
49 | } | ||
50 | } | ||
51 | |||
52 | export { | ||
53 | ModelCache | ||
54 | } | ||