1 import { Model } from 'sequelize-typescript'
2 import * as Bluebird from 'bluebird'
3 import { logger } from '@server/helpers/logger'
9 | 'load-video-immutable-id'
10 | 'load-video-immutable-url'
17 private static instance: ModelCache
19 private readonly localCache: { [id in ModelCacheType]: Map<string, any> } = {
20 'local-account-name': new Map(),
21 'local-actor-name': new Map(),
22 'local-actor-url': new Map(),
23 'load-video-immutable-id': new Map(),
24 'load-video-immutable-url': new Map()
27 private readonly deleteIds: {
28 [deleteKey in DeleteKey]: Map<number, { cacheType: ModelCacheType, key: string }[]>
33 private constructor () {
36 static get Instance () {
37 return this.instance || (this.instance = new this())
40 doCache<T extends Model> (options: {
41 cacheType: ModelCacheType
44 whitelist?: () => boolean
47 const { cacheType, key, fun, whitelist, deleteKey } = options
49 if (whitelist && whitelist() !== true) return fun()
51 const cache = this.localCache[cacheType]
54 logger.debug('Model cache hit for %s -> %s.', cacheType, key)
55 return Bluebird.resolve<T>(cache.get(key))
58 return fun().then(m => {
61 if (!whitelist || whitelist()) cache.set(key, m)
64 const map = this.deleteIds[deleteKey]
65 if (!map.has(m.id)) map.set(m.id, [])
67 const a = map.get(m.id)
68 a.push({ cacheType, key })
75 invalidateCache (deleteKey: DeleteKey, modelId: number) {
76 const map = this.deleteIds[deleteKey]
78 if (!map.has(modelId)) return
80 for (const toDelete of map.get(modelId)) {
81 logger.debug('Removing %s -> %d of model cache %s -> %s.', deleteKey, modelId, toDelete.cacheType, toDelete.key)
82 this.localCache[toDelete.cacheType].delete(toDelete.key)