70 lines
No EOL
2.3 KiB
TypeScript
70 lines
No EOL
2.3 KiB
TypeScript
// Store sessions to memory (lost on restart)
|
|
import { MemoryLevel } from "memory-level";
|
|
import { RedisClient } from "bun"
|
|
|
|
interface SecondaryStorage {
|
|
get: (key: string) => Promise<unknown>;
|
|
set: (key: string, value: string, ttl?: number) => Promise<void>;
|
|
delete: (key: string) => Promise<void>;
|
|
}
|
|
|
|
/* 01 - Memory storage */
|
|
const memAuthSession = new MemoryLevel();
|
|
export const storageMem: SecondaryStorage = {
|
|
get: async (key) => {
|
|
if (await memAuthSession.has(`${key}_exp`)) {
|
|
const cur = Math.floor(Date.now() / 1000);
|
|
const exp = parseInt(await memAuthSession.get(`${key}_exp`) ?? "0");
|
|
if (cur >= exp) return null;
|
|
}
|
|
const value = await memAuthSession.get(key);
|
|
return value ? value : null;
|
|
},
|
|
set: async (key, value, ttl) => {
|
|
if (ttl) await memAuthSession.put(`${key}_exp`, Math.floor((Date.now() / 1000) + ttl).toString());
|
|
await memAuthSession.put(key, value);
|
|
},
|
|
delete: async (key) => {
|
|
await memAuthSession.del(key);
|
|
if (await memAuthSession.has(`${key}_exp`)) await memAuthSession.del(`${key}_exp`);
|
|
}
|
|
}
|
|
|
|
async function cleanup() {
|
|
const cur = Math.floor(Date.now() / 1000);
|
|
|
|
for await (const k of memAuthSession.keys()) {
|
|
if (k.endsWith("_exp")) {
|
|
const exp = parseInt(await memAuthSession.get(k) ?? "0");
|
|
|
|
if (cur >= exp) {
|
|
await memAuthSession.del(k);
|
|
await memAuthSession.del(k.slice(0, -4));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
setInterval(cleanup, 10000);
|
|
|
|
/* 02 - Redis storage (VK) */
|
|
const redisInstance: RedisClient | null = process.env.REDIS_URL ? new RedisClient(process.env.REDIS_URL) : null;
|
|
|
|
export const storageRedis: SecondaryStorage = {
|
|
get: async (key) => {
|
|
if (redisInstance === null) throw Error("Redis support is not yet enabled. Please define REDIS_URL in .env file");
|
|
return await redisInstance.get(key);
|
|
},
|
|
set: async (key, value, ttl) => {
|
|
if (redisInstance === null) throw Error("Redis support is not yet enabled. Please define REDIS_URL in .env file");
|
|
if (ttl) {
|
|
await redisInstance.setex(key, ttl, value);
|
|
} else {
|
|
await redisInstance.set(key, value);
|
|
}
|
|
},
|
|
delete: async (key) => {
|
|
if (redisInstance === null) throw Error("Redis support is not yet enabled. Please define REDIS_URL in .env file");
|
|
await redisInstance.del(key);
|
|
}
|
|
} |