mirror of
https://github.com/BluemediaDev/muse.git
synced 2025-06-28 09:42:41 +02:00
Add FileCache model
This commit is contained in:
parent
d805da906a
commit
04c7e61fc0
7 changed files with 26 additions and 9 deletions
56
src/services/key-value-cache.ts
Normal file
56
src/services/key-value-cache.ts
Normal file
|
@ -0,0 +1,56 @@
|
|||
import {injectable} from 'inversify';
|
||||
import {KeyValueCache} from '../models/index.js';
|
||||
import debug from '../utils/debug.js';
|
||||
|
||||
type Seconds = number;
|
||||
|
||||
type Options = {
|
||||
expiresIn: Seconds;
|
||||
key?: string;
|
||||
};
|
||||
|
||||
const futureTimeToDate = (time: Seconds) => new Date(new Date().getTime() + (time * 1000));
|
||||
|
||||
@injectable()
|
||||
export default class KeyValueCacheProvider {
|
||||
async wrap<T extends [...any[], Options], F>(func: (...options: any) => Promise<F>, ...options: T): Promise<F> {
|
||||
if (options.length === 0) {
|
||||
throw new Error('Missing cache options');
|
||||
}
|
||||
|
||||
const functionArgs = options.slice(0, options.length - 1);
|
||||
|
||||
const {
|
||||
key = JSON.stringify(functionArgs),
|
||||
expiresIn,
|
||||
} = options[options.length - 1] as Options;
|
||||
|
||||
if (key.length < 4) {
|
||||
throw new Error(`Cache key ${key} is too short.`);
|
||||
}
|
||||
|
||||
const cachedResult = await KeyValueCache.findByPk(key);
|
||||
|
||||
if (cachedResult) {
|
||||
if (new Date() < cachedResult.expiresAt) {
|
||||
debug(`Cache hit: ${key}`);
|
||||
return JSON.parse(cachedResult.value) as F;
|
||||
}
|
||||
|
||||
await cachedResult.destroy();
|
||||
}
|
||||
|
||||
debug(`Cache miss: ${key}`);
|
||||
|
||||
const result = await func(...options as any[]);
|
||||
|
||||
// Save result
|
||||
await KeyValueCache.upsert({
|
||||
key,
|
||||
value: JSON.stringify(result),
|
||||
expiresAt: futureTimeToDate(expiresIn),
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue