github-profile-trophy-reiyu.../src/config/cache.ts
Ömer 611e5bf0b6
fix: correct content-type for HTML pages and allow password-less redis (#418)
* fix: correct content-type for HTML pages and allow password-less redis

Set Content-Type to 'text/html' instead of 'text' for index and
error page responses, since both return HTML content.

Also change redis username/password fallback from empty string to
undefined so that the driver skips AUTH when no credentials are
configured. An empty string causes AUTH to be sent which fails on
servers with no password set.

Fixes #387, fixes #388

* fix: revert unintended formatting change to pass deno fmt check

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-04 14:51:25 +09:00

74 lines
1.8 KiB
TypeScript

import { Bulk, connect, Redis } from "../../deps.ts";
import { Logger } from "../Helpers/Logger.ts";
import { CONSTANTS } from "../utils.ts";
const enableCache: boolean = Deno.env.get("ENABLE_REDIS") === "true";
// https://developer.redis.com/develop/deno/
class CacheProvider {
private static instance: CacheProvider;
public client: Redis | null = null;
private constructor() {}
static getInstance(): CacheProvider {
if (!CacheProvider.instance) {
CacheProvider.instance = new CacheProvider();
}
return CacheProvider.instance;
}
async connect(): Promise<void> {
if (!enableCache) return;
this.client = await connect({
hostname: Deno.env.get("REDIS_HOST") || "",
port: Number(Deno.env.get("REDIS_PORT")) || 6379,
username: Deno.env.get("REDIS_USERNAME") || undefined,
password: Deno.env.get("REDIS_PASSWORD") || undefined,
});
}
async get(key: string): Promise<Bulk | undefined> {
if (!enableCache) return undefined;
try {
if (!this.client) {
await this.connect();
}
return await this.client?.get(key);
} catch {
return undefined;
}
}
async set(key: string, value: string): Promise<void> {
if (!enableCache) return;
try {
if (!this.client) {
await this.connect();
}
await this.client?.set(key, value, {
px: CONSTANTS.REDIS_TTL,
});
} catch (e) {
Logger.error(`Failed to set cache: ${e.message}`);
}
}
async del(key: string): Promise<void> {
if (!enableCache) return;
try {
if (!this.client) {
await this.connect();
}
await this.client?.del(key);
} catch (e) {
Logger.error(`Failed to delete cache: ${e.message}`);
}
}
}
export const cacheProvider = CacheProvider.getInstance();