feat: integrate use of ebvalidated envs

This commit is contained in:
Ritesh Ghosh
2025-05-11 13:07:04 +05:30
parent fc92194407
commit 5e028771f0
4 changed files with 64 additions and 57 deletions
+25 -18
View File
@@ -1,47 +1,54 @@
import { config } from "dotenv";
import { Redis } from "ioredis"; import { Redis } from "ioredis";
import { env } from "./env.js";
config();
export class AniwatchAPICache { export class AniwatchAPICache {
private _client: Redis | null; private static instance: AniwatchAPICache | null = null;
private client: Redis | null;
public isOptional: boolean = true; public isOptional: boolean = true;
static DEFAULT_CACHE_EXPIRY_SECONDS = 60 as const; static DEFAULT_CACHE_EXPIRY_SECONDS = 60 as const;
static CACHE_EXPIRY_HEADER_NAME = "X-ANIWATCH-CACHE-EXPIRY" as const; static CACHE_EXPIRY_HEADER_NAME = "X-ANIWATCH-CACHE-EXPIRY" as const;
constructor() { constructor() {
const redisConnURL = process.env?.ANIWATCH_API_REDIS_CONN_URL; const redisConnURL = env.ANIWATCH_API_REDIS_CONN_URL;
this.isOptional = !Boolean(redisConnURL); 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) { static getInstance() {
if (this.isOptional) return; if (!AniwatchAPICache.instance) {
return this._client?.set(key, value); AniwatchAPICache.instance = new AniwatchAPICache();
}
return AniwatchAPICache.instance;
} }
get(key: string | Buffer) { // set(key: string | Buffer, value: string | Buffer | number) {
if (this.isOptional) return; // if (this.isOptional) return;
return this._client?.get(key); // 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 * @param expirySeconds set to 60 by default
*/ */
async getOrSet<T>( async getOrSet<T>(
setCB: () => Promise<T>, dataGetter: () => Promise<T>,
key: string | Buffer, key: string | Buffer,
expirySeconds: number = AniwatchAPICache.DEFAULT_CACHE_EXPIRY_SECONDS expirySeconds: number = AniwatchAPICache.DEFAULT_CACHE_EXPIRY_SECONDS
) { ) {
const cachedData = this.isOptional const cachedData = this.isOptional
? null ? null
: (await this._client?.get(key)) || null; : (await this.client?.get?.(key)) || null;
let data = JSON.parse(String(cachedData)) as T; let data = JSON.parse(String(cachedData)) as T;
if (!data) { if (!data) {
data = await setCB(); data = await dataGetter();
await this._client?.set( await this.client?.set?.(
key, key,
JSON.stringify(data), JSON.stringify(data),
"EX", "EX",
@@ -52,4 +59,4 @@ export class AniwatchAPICache {
} }
} }
export const cache = new AniwatchAPICache(); export const cache = AniwatchAPICache.getInstance();
+10 -12
View File
@@ -1,17 +1,15 @@
import { config } from "dotenv";
import { cors } from "hono/cors"; import { cors } from "hono/cors";
import { env } from "./env.js";
config(); const DEFAULT_ALLOWED_ORIGINS = ["http://localhost:4000", "*"];
const allowedOrigins = process.env.ANIWATCH_API_CORS_ALLOWED_ORIGINS const allowedOrigins = env.ANIWATCH_API_CORS_ALLOWED_ORIGINS
? process.env.ANIWATCH_API_CORS_ALLOWED_ORIGINS.split(",") ? env.ANIWATCH_API_CORS_ALLOWED_ORIGINS.split(",")
: ["http://localhost:4000", "*"]; : DEFAULT_ALLOWED_ORIGINS;
const corsConfig = cors({ export const corsConfig = cors({
allowMethods: ["GET"], allowMethods: ["GET"],
maxAge: 600, maxAge: 600,
credentials: true, credentials: true,
origin: allowedOrigins, origin: allowedOrigins,
}); });
export default corsConfig;
+13 -12
View File
@@ -1,27 +1,28 @@
import { HiAnimeError } from "aniwatch"; import { HiAnimeError } from "aniwatch";
import type { ErrorHandler, NotFoundHandler } from "hono"; import type { ErrorHandler, NotFoundHandler } from "hono";
import type { ContentfulStatusCode } from "hono/utils/http-status"; import type { ContentfulStatusCode } from "hono/utils/http-status";
import { logger } from "./logger.js";
const errResp: { status: ContentfulStatusCode; message: string } = { const errResp: { status: ContentfulStatusCode; message: string } = {
status: 500, status: 500,
message: "Internal Server Error", message: "Internal Server Error",
}; };
export const errorHandler: ErrorHandler = (err, c) => { export const errorHandler: ErrorHandler = (err, c) => {
console.error(err); logger.error(JSON.stringify(err));
if (err instanceof HiAnimeError) { if (err instanceof HiAnimeError) {
errResp.status = err.status as ContentfulStatusCode; errResp.status = err.status as ContentfulStatusCode;
errResp.message = err.message; errResp.message = err.message;
} }
return c.json(errResp, errResp.status); return c.json(errResp, errResp.status);
}; };
export const notFoundHandler: NotFoundHandler = (c) => { export const notFoundHandler: NotFoundHandler = (c) => {
errResp.status = 404; errResp.status = 404;
errResp.message = "Not Found"; errResp.message = "Not Found";
console.error(errResp); logger.error(JSON.stringify(errResp));
return c.json(errResp, errResp.status); return c.json(errResp, errResp.status);
}; };
+16 -15
View File
@@ -1,21 +1,22 @@
import { config } from "dotenv";
import { rateLimiter } from "hono-rate-limiter"; import { rateLimiter } from "hono-rate-limiter";
import { getConnInfo } from "@hono/node-server/conninfo"; import { getConnInfo } from "@hono/node-server/conninfo";
import { env } from "./env.js";
config();
export const ratelimit = rateLimiter({ export const ratelimit = rateLimiter({
windowMs: Number(process.env.ANIWATCH_API_WINDOW_MS) || 30 * 60 * 1000, windowMs: env.ANIWATCH_API_WINDOW_MS,
limit: Number(process.env.ANIWATCH_API_MAX_REQS) || 6, limit: env.ANIWATCH_API_MAX_REQS,
standardHeaders: "draft-7", standardHeaders: "draft-7",
keyGenerator(c) { keyGenerator(c) {
const { remote } = getConnInfo(c); const { remote } = getConnInfo(c);
const key = const key =
`${String(remote.addressType)}_` + `${String(remote.addressType)}_` +
`${String(remote.address)}:${String(remote.port)}`; `${String(remote.address)}:${String(remote.port)}`;
return key; return key;
}, },
handler: (c) => handler: (c) =>
c.json({ status: 429, message: "Too Many Requests 😵" }, { status: 429 }), c.json(
{ status: 429, message: "Too Many Requests 😵" },
{ status: 429 }
),
}); });