2023-07-31 07:34:36 -05:00
|
|
|
import { remove } from 'fs-extra/esm'
|
|
|
|
import { logger } from '../../../helpers/logger.js'
|
2021-08-27 07:32:44 -05:00
|
|
|
import memoizee from 'memoizee'
|
2018-07-12 12:02:00 -05:00
|
|
|
|
2021-02-16 09:25:53 -06:00
|
|
|
type GetFilePathResult = { isOwned: boolean, path: string, downloadName?: string } | undefined
|
2019-04-23 02:50:57 -05:00
|
|
|
|
2023-06-06 08:59:51 -05:00
|
|
|
export abstract class AbstractSimpleFileCache <T> {
|
2018-07-12 12:02:00 -05:00
|
|
|
|
2019-04-23 02:50:57 -05:00
|
|
|
getFilePath: (params: T) => Promise<GetFilePathResult>
|
2018-07-12 12:02:00 -05:00
|
|
|
|
2019-04-23 02:50:57 -05:00
|
|
|
abstract getFilePathImpl (params: T): Promise<GetFilePathResult>
|
2018-07-12 12:02:00 -05:00
|
|
|
|
|
|
|
// Load and save the remote file, then return the local path from filesystem
|
2019-04-23 02:50:57 -05:00
|
|
|
protected abstract loadRemoteFile (key: string): Promise<GetFilePathResult>
|
2018-07-12 12:02:00 -05:00
|
|
|
|
2018-07-16 07:22:16 -05:00
|
|
|
init (max: number, maxAge: number) {
|
2024-02-22 03:12:04 -06:00
|
|
|
this.getFilePath = memoizee(this.getFilePathImpl.bind(this), {
|
2018-07-16 07:22:16 -05:00
|
|
|
maxAge,
|
2019-04-17 03:07:00 -05:00
|
|
|
max,
|
|
|
|
promise: true,
|
2019-05-28 02:36:46 -05:00
|
|
|
dispose: (result?: GetFilePathResult) => {
|
|
|
|
if (result && result.isOwned !== true) {
|
2019-04-23 02:50:57 -05:00
|
|
|
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 }))
|
|
|
|
}
|
2018-07-12 12:02:00 -05:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|