aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/model-cache.ts
blob: bfa163b6b5a3438086b58a1f23231fbe996b3876 (plain) (blame)
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
import { Model } from 'sequelize-typescript'
import * as Bluebird from 'bluebird'
import { logger } from '@server/helpers/logger'

type ModelCacheType =
  'local-account-name'
  | 'local-actor-name'
  | 'local-actor-url'

class ModelCache {

  private static instance: ModelCache

  private readonly localCache: { [id in ModelCacheType]: Map<string, any> } = {
    'local-account-name': new Map(),
    'local-actor-name': new Map(),
    'local-actor-url': new Map()
  }

  private constructor () {
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }

  doCache<T extends Model> (options: {
    cacheType: ModelCacheType
    key: string
    fun: () => Bluebird<T>
    whitelist?: () => boolean
  }) {
    const { cacheType, key, fun, whitelist } = options

    if (whitelist && whitelist() !== true) return fun()

    const cache = this.localCache[cacheType]

    if (cache.has(key)) {
      logger.debug('Model cache hit for %s -> %s.', cacheType, key)
      return Bluebird.resolve<T>(cache.get(key))
    }

    return fun().then(m => {
      if (!whitelist || whitelist()) cache.set(key, m)

      return m
    })
  }
}

export {
  ModelCache
}