feat: integrate use of ebvalidated envs
This commit is contained in:
+25
-18
@@ -1,47 +1,54 @@
|
||||
import { config } from "dotenv";
|
||||
import { Redis } from "ioredis";
|
||||
|
||||
config();
|
||||
import { env } from "./env.js";
|
||||
|
||||
export class AniwatchAPICache {
|
||||
private _client: Redis | null;
|
||||
private static instance: AniwatchAPICache | null = null;
|
||||
|
||||
private client: Redis | null;
|
||||
public isOptional: boolean = true;
|
||||
|
||||
static DEFAULT_CACHE_EXPIRY_SECONDS = 60 as const;
|
||||
static CACHE_EXPIRY_HEADER_NAME = "X-ANIWATCH-CACHE-EXPIRY" as const;
|
||||
|
||||
constructor() {
|
||||
const redisConnURL = process.env?.ANIWATCH_API_REDIS_CONN_URL;
|
||||
const redisConnURL = env.ANIWATCH_API_REDIS_CONN_URL;
|
||||
this.isOptional = !Boolean(redisConnURL);
|
||||
this._client = this.isOptional ? null : new Redis(String(redisConnURL));
|
||||
this.client = this.isOptional ? null : new Redis(String(redisConnURL));
|
||||
}
|
||||
|
||||
set(key: string | Buffer, value: string | Buffer | number) {
|
||||
if (this.isOptional) return;
|
||||
return this._client?.set(key, value);
|
||||
static getInstance() {
|
||||
if (!AniwatchAPICache.instance) {
|
||||
AniwatchAPICache.instance = new AniwatchAPICache();
|
||||
}
|
||||
return AniwatchAPICache.instance;
|
||||
}
|
||||
|
||||
get(key: string | Buffer) {
|
||||
if (this.isOptional) return;
|
||||
return this._client?.get(key);
|
||||
}
|
||||
// set(key: string | Buffer, value: string | Buffer | number) {
|
||||
// if (this.isOptional) return;
|
||||
// return this.client?.set(key, value);
|
||||
// }
|
||||
|
||||
// get(key: string | Buffer) {
|
||||
// if (this.isOptional) return;
|
||||
// return this.client?.get(key);
|
||||
// }
|
||||
|
||||
/**
|
||||
* @param expirySeconds set to 60 by default
|
||||
*/
|
||||
async getOrSet<T>(
|
||||
setCB: () => Promise<T>,
|
||||
dataGetter: () => Promise<T>,
|
||||
key: string | Buffer,
|
||||
expirySeconds: number = AniwatchAPICache.DEFAULT_CACHE_EXPIRY_SECONDS
|
||||
) {
|
||||
const cachedData = this.isOptional
|
||||
? null
|
||||
: (await this._client?.get(key)) || null;
|
||||
: (await this.client?.get?.(key)) || null;
|
||||
let data = JSON.parse(String(cachedData)) as T;
|
||||
|
||||
if (!data) {
|
||||
data = await setCB();
|
||||
await this._client?.set(
|
||||
data = await dataGetter();
|
||||
await this.client?.set?.(
|
||||
key,
|
||||
JSON.stringify(data),
|
||||
"EX",
|
||||
@@ -52,4 +59,4 @@ export class AniwatchAPICache {
|
||||
}
|
||||
}
|
||||
|
||||
export const cache = new AniwatchAPICache();
|
||||
export const cache = AniwatchAPICache.getInstance();
|
||||
|
||||
Reference in New Issue
Block a user