aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/files-cache/shared/abstract-simple-file-cache.ts
blob: 6fab322cdf8f2b09632503fdd048d91f443b4efe (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
import { remove } from 'fs-extra'
import { logger } from '../../../helpers/logger'
import memoizee from 'memoizee'

type GetFilePathResult = { isOwned: boolean, path: string, downloadName?: string } | undefined

export abstract class AbstractSimpleFileCache <T> {

  getFilePath: (params: T) => Promise<GetFilePathResult>

  abstract getFilePathImpl (params: T): Promise<GetFilePathResult>

  // Load and save the remote file, then return the local path from filesystem
  protected abstract loadRemoteFile (key: string): Promise<GetFilePathResult>

  init (max: number, maxAge: number) {
    this.getFilePath = memoizee(this.getFilePathImpl, {
      maxAge,
      max,
      promise: true,
      dispose: (result?: GetFilePathResult) => {
        if (result && result.isOwned !== true) {
          remove(result.path)
            .then(() => logger.debug('%s removed from %s', result.path, this.constructor.name))
            .catch(err => logger.error('Cannot remove %s from cache %s.', result.path, this.constructor.name, { err }))
        }
      }
    })
  }
}