style: formatting changes

This commit is contained in:
Ritesh Ghosh
2025-04-15 00:11:33 +05:30
parent f5cd3415d8
commit f7af9c890a
2 changed files with 78 additions and 68 deletions
+43 -38
View File
@@ -4,47 +4,52 @@ import { Redis } from "ioredis";
config(); config();
export class AniwatchAPICache { export class AniwatchAPICache {
private _client: Redis | 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 = process.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) { set(key: string | Buffer, value: string | Buffer | number) {
if (this.isOptional) return; if (this.isOptional) return;
return this._client?.set(key, value); return this._client?.set(key, value);
} }
get(key: string | Buffer) { get(key: string | Buffer) {
if (this.isOptional) return; if (this.isOptional) return;
return this._client?.get(key); 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>, setCB: () => 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 setCB();
await this._client?.set(key, JSON.stringify(data), "EX", expirySeconds); await this._client?.set(
key,
JSON.stringify(data),
"EX",
expirySeconds
);
}
return data;
} }
return data;
}
} }
export const cache = new AniwatchAPICache(); export const cache = new AniwatchAPICache();
+35 -30
View File
@@ -5,8 +5,8 @@ import corsConfig from "./config/cors.js";
import { ratelimit } from "./config/ratelimit.js"; import { ratelimit } from "./config/ratelimit.js";
import { import {
cacheConfigSetter, cacheConfigSetter,
cacheControlMiddleware, cacheControlMiddleware,
} from "./middleware/cache.js"; } from "./middleware/cache.js";
import { hianimeRouter } from "./routes/hianime.js"; import { hianimeRouter } from "./routes/hianime.js";
@@ -36,52 +36,57 @@ app.use(cacheControlMiddleware);
// or other issues if you do. // or other issues if you do.
const ISNT_PERSONAL_DEPLOYMENT = Boolean(ANIWATCH_API_HOSTNAME); const ISNT_PERSONAL_DEPLOYMENT = Boolean(ANIWATCH_API_HOSTNAME);
if (ISNT_PERSONAL_DEPLOYMENT) { if (ISNT_PERSONAL_DEPLOYMENT) {
app.use(ratelimit); app.use(ratelimit);
} }
app.use("/", serveStatic({ root: "public" })); app.use("/", serveStatic({ root: "public" }));
app.get("/health", (c) => c.text("daijoubu", { status: 200 })); app.get("/health", (c) => c.text("daijoubu", { status: 200 }));
app.get("/v", async (c) => app.get("/v", async (c) =>
c.text( c.text(
`v${"version" in pkgJson && pkgJson?.version ? pkgJson.version : "-1"}` `v${"version" in pkgJson && pkgJson?.version ? pkgJson.version : "-1"}`
) )
); );
app.use(cacheConfigSetter(BASE_PATH.length)); app.use(cacheConfigSetter(BASE_PATH.length));
app.basePath(BASE_PATH).route("/hianime", hianimeRouter); app.basePath(BASE_PATH).route("/hianime", hianimeRouter);
app app.basePath(BASE_PATH).get("/anicrush", (c) =>
.basePath(BASE_PATH) c.text("Anicrush could be implemented in future.")
.get("/anicrush", (c) => c.text("Anicrush could be implemented in future.")); );
app.notFound(notFoundHandler); app.notFound(notFoundHandler);
app.onError(errorHandler); app.onError(errorHandler);
// NOTE: this env is "required" for vercel deployments // NOTE: this env is "required" for vercel deployments
if (!Boolean(process.env?.ANIWATCH_API_VERCEL_DEPLOYMENT)) { if (!Boolean(process.env?.ANIWATCH_API_VERCEL_DEPLOYMENT)) {
serve({ serve({
port: PORT, port: PORT,
fetch: app.fetch, fetch: app.fetch,
}).addListener("listening", () => }).addListener("listening", () =>
console.info( console.info(
"\x1b[1;36m" + `aniwatch-api at http://localhost:${PORT}` + "\x1b[0m" "\x1b[1;36m" +
) `aniwatch-api at http://localhost:${PORT}` +
); "\x1b[0m"
)
);
// NOTE: remove the `if` block below for personal deployments // NOTE: remove the `if` block below for personal deployments
if (ISNT_PERSONAL_DEPLOYMENT) { if (ISNT_PERSONAL_DEPLOYMENT) {
const interval = 9 * 60 * 1000; // 9mins const interval = 9 * 60 * 1000; // 9mins
// don't sleep // don't sleep
setInterval(() => { setInterval(() => {
console.log("aniwatch-api HEALTH_CHECK at", new Date().toISOString()); console.log(
https "aniwatch-api HEALTH_CHECK at",
.get(`https://${ANIWATCH_API_HOSTNAME}/health`) new Date().toISOString()
.on("error", (err) => { );
console.error(err.message); https
}); .get(`https://${ANIWATCH_API_HOSTNAME}/health`)
}, interval); .on("error", (err) => {
} console.error(err.message);
});
}, interval);
}
} }
export default app; export default app;