abstract-video-static-file-cache.ts 1.0 KB

123456789101112131415161718192021222324252627282930
  1. import { remove } from 'fs-extra'
  2. import { logger } from '../../helpers/logger'
  3. import * as memoizee from 'memoizee'
  4. type GetFilePathResult = { isOwned: boolean, path: string } | undefined
  5. export abstract class AbstractVideoStaticFileCache <T> {
  6. getFilePath: (params: T) => Promise<GetFilePathResult>
  7. abstract getFilePathImpl (params: T): Promise<GetFilePathResult>
  8. // Load and save the remote file, then return the local path from filesystem
  9. protected abstract loadRemoteFile (key: string): Promise<GetFilePathResult>
  10. init (max: number, maxAge: number) {
  11. this.getFilePath = memoizee(this.getFilePathImpl, {
  12. maxAge,
  13. max,
  14. promise: true,
  15. dispose: (result?: GetFilePathResult) => {
  16. if (result && result.isOwned !== true) {
  17. remove(result.path)
  18. .then(() => logger.debug('%s removed from %s', result.path, this.constructor.name))
  19. .catch(err => logger.error('Cannot remove %s from cache %s.', result.path, this.constructor.name, { err }))
  20. }
  21. }
  22. })
  23. }
  24. }