1 import { Model } from 'sequelize-typescript'
2 import { logger } from '@server/helpers/logger'
8 | 'load-video-immutable-id'
9 | 'load-video-immutable-url'
16 private static instance: ModelCache
18 private readonly localCache: { [id in ModelCacheType]: Map<string, any> } = {
19 'local-account-name': new Map(),
20 'local-actor-name': new Map(),
21 'local-actor-url': new Map(),
22 'load-video-immutable-id': new Map(),
23 'load-video-immutable-url': new Map()
26 private readonly deleteIds: {
27 [deleteKey in DeleteKey]: Map<number, { cacheType: ModelCacheType, key: string }[]>
32 private constructor () {
35 static get Instance () {
36 return this.instance || (this.instance = new this())
39 doCache<T extends Model> (options: {
40 cacheType: ModelCacheType
43 whitelist?: () => boolean
46 const { cacheType, key, fun, whitelist, deleteKey } = options
48 if (whitelist && whitelist() !== true) return fun()
50 const cache = this.localCache[cacheType]
53 logger.debug('Model cache hit for %s -> %s.', cacheType, key)
54 return Promise.resolve<T>(cache.get(key))
57 return fun().then(m => {
60 if (!whitelist || whitelist()) cache.set(key, m)
63 const map = this.deleteIds[deleteKey]
64 if (!map.has(m.id)) map.set(m.id, [])
66 const a = map.get(m.id)
67 a.push({ cacheType, key })
74 invalidateCache (deleteKey: DeleteKey, modelId: number) {
75 const map = this.deleteIds[deleteKey]
77 if (!map.has(modelId)) return
79 for (const toDelete of map.get(modelId)) {
80 logger.debug('Removing %s -> %d of model cache %s -> %s.', deleteKey, modelId, toDelete.cacheType, toDelete.key)
81 this.localCache[toDelete.cacheType].delete(toDelete.key)