/
cache.ts
65 lines (54 loc) · 1.86 KB
/
cache.ts
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import Keyv, { Options } from 'keyv';
import ms from 'ms';
import env from './env';
import logger from './logger';
import { getConfigFromEnv } from './utils/get-config-from-env';
import { validateEnv } from './utils/validate-env';
let cache: Keyv | null = null;
let schemaCache: Keyv | null = null;
export function getCache(): { cache: Keyv | null; schemaCache: Keyv | null } {
if (env.CACHE_ENABLED === true && cache === null) {
validateEnv(['CACHE_NAMESPACE', 'CACHE_TTL', 'CACHE_STORE']);
cache = getKeyvInstance(ms(env.CACHE_TTL as string));
cache.on('error', (err) => logger.warn(err, `[cache] ${err}`));
}
if (env.CACHE_SCHEMA !== false && schemaCache === null) {
schemaCache = getKeyvInstance(typeof env.CACHE_SCHEMA === 'string' ? ms(env.CACHE_SCHEMA) : undefined);
schemaCache.on('error', (err) => logger.warn(err, `[cache] ${err}`));
}
return { cache, schemaCache };
}
export async function flushCaches(): Promise<void> {
const { schemaCache, cache } = getCache();
await schemaCache?.clear();
await cache?.clear();
}
function getKeyvInstance(ttl: number | undefined): Keyv {
switch (env.CACHE_STORE) {
case 'redis':
return new Keyv(getConfig('redis', ttl));
case 'memcache':
return new Keyv(getConfig('memcache', ttl));
case 'memory':
default:
return new Keyv(getConfig('memory', ttl));
}
}
function getConfig(store: 'memory' | 'redis' | 'memcache' = 'memory', ttl: number | undefined): Options<any> {
const config: Options<any> = {
namespace: env.CACHE_NAMESPACE,
ttl,
};
if (store === 'redis') {
const KeyvRedis = require('@keyv/redis');
config.store = new KeyvRedis(env.CACHE_REDIS || getConfigFromEnv('CACHE_REDIS_'), {
commandTimeout: 500,
retryStrategy: false,
});
}
if (store === 'memcache') {
const KeyvMemcache = require('keyv-memcache');
config.store = new KeyvMemcache(env.CACHE_MEMCACHE);
}
return config;
}