sso-core/src/lib/server/cache-backend.ts
2025-02-23 12:21:09 +02:00

52 lines
1.2 KiB
TypeScript

import { env } from '$env/dynamic/private';
import KeyvValkey from '@keyv/valkey';
import { createCache, type Cache } from 'cache-manager';
import { CacheableMemory, Keyv } from 'cacheable';
export class CacheBackend {
private static cache: Cache;
/**
* Set a cached value
* @param key Key to set
* @param data Data to set
* @param ttl Time-to-live in milliseconds
*/
public static async set<T = unknown>(key: string, data: T, ttl?: number): Promise<T> {
return CacheBackend.cache.set(key, data, ttl);
}
/**
* Get a cached value
* @param key Key to retrieve from cache
* @returns Value
*/
public static async get<T = unknown>(key: string): Promise<T | undefined> {
return CacheBackend.cache.get(key) as T;
}
/**
* Delete a cached value
* @param key Key to delete from cache
* @returns Success
*/
public static async del(key: string) {
return CacheBackend.cache.del(key);
}
/**
* Initialize configured cache backend
*/
public static async init() {
CacheBackend.cache = createCache({
stores: [
new Keyv({
store: env.VALKEY_URI
? new KeyvValkey(env.VALKEY_URI)
: new CacheableMemory({ ttl: 3600000, lruSize: 5000 })
})
]
});
}
}