Merge pull request #122 from ghoshRitesh12/feature/proper-envs
feature: add proper envs and logging support
This commit is contained in:
@@ -23,4 +23,7 @@ jobs:
|
||||
run: npm i
|
||||
|
||||
- name: Check lint
|
||||
run: npm run lint:ci
|
||||
run: npm run lint
|
||||
|
||||
- name: Check prettier
|
||||
run: npm run format:check
|
||||
@@ -0,0 +1,6 @@
|
||||
// Skip Husky install in production and CI
|
||||
if (process.env.NODE_ENV === "production" || process.env.CI === "true") {
|
||||
process.exit(0);
|
||||
}
|
||||
const husky = (await import("husky")).default;
|
||||
console.log(husky());
|
||||
+3
-17
@@ -1,35 +1,21 @@
|
||||
# [2.12.0](https://github.com/ghoshRitesh12/aniwatch-api/compare/v2.11.3...v2.12.0) (2025-04-14)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **getNextEpisodeSchedule:** add `/anime/:animeId/next-episode-schedule` endpoint ([f5cd341](https://github.com/ghoshRitesh12/aniwatch-api/commit/f5cd3415d8134da1ab1e3b3f8f9be6b5212aa353))
|
||||
|
||||
|
||||
- **getNextEpisodeSchedule:** add `/anime/:animeId/next-episode-schedule` endpoint ([f5cd341](https://github.com/ghoshRitesh12/aniwatch-api/commit/f5cd3415d8134da1ab1e3b3f8f9be6b5212aa353))
|
||||
|
||||
## [2.11.3](https://github.com/ghoshRitesh12/aniwatch-api/compare/v2.11.2...v2.11.3) (2025-03-20)
|
||||
|
||||
|
||||
|
||||
## [2.11.2](https://github.com/ghoshRitesh12/aniwatch-api/compare/v2.11.1...v2.11.2) (2025-03-15)
|
||||
|
||||
|
||||
|
||||
## [2.11.1](https://github.com/ghoshRitesh12/aniwatch-api/compare/v2.11.0...v2.11.1) (2025-01-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **ts build error:** fixed ts build error due to conflicting types ([cb5a467](https://github.com/ghoshRitesh12/aniwatch-api/commit/cb5a4672a8c3b0729bbb4522a3af252f7b336b97))
|
||||
|
||||
|
||||
- **ts build error:** fixed ts build error due to conflicting types ([cb5a467](https://github.com/ghoshRitesh12/aniwatch-api/commit/cb5a4672a8c3b0729bbb4522a3af252f7b336b97))
|
||||
|
||||
# [2.11.0](https://github.com/ghoshRitesh12/aniwatch-api/compare/v2.10.0...v2.11.0) (2024-12-25)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **`/qtip`:** add new `/qtip` endpoint ([f0acd89](https://github.com/ghoshRitesh12/aniwatch-api/commit/f0acd89d87e5e62c12e20a95225ca9261fefe411))
|
||||
|
||||
|
||||
|
||||
- **`/qtip`:** add new `/qtip` endpoint ([f0acd89](https://github.com/ghoshRitesh12/aniwatch-api/commit/f0acd89d87e5e62c12e20a95225ca9261fefe411))
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
# <p align="center">Aniwatch API</p>
|
||||
|
||||
<div align="center">
|
||||
A free RESTful API serving anime information from <a href="https://hianime.to" target="_blank">hianime.to</a>
|
||||
A free RESTful API serving anime information from <a href="https://hianimez.to" target="_blank">hianimez.to</a>
|
||||
|
||||
<br/>
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
> [!IMPORTANT]
|
||||
>
|
||||
> 1. [https://api-aniwatch.onrender.com](https://api-aniwatch.onrender.com/) is only meant to demo the API and has rate-limiting enabled to minimize bandwidth consumption. It is recommended to deploy your own instance for personal use by customizing the API as you need it to be.
|
||||
> 2. This API is just an unofficial API for [hianime.to](https://hianime.to) and is in no other way officially related to the same.
|
||||
> 2. This API is just an unofficial API for [hianimez.to](https://hianimez.to) and is in no other way officially related to the same.
|
||||
> 3. The content that this API provides is not mine, nor is it hosted by me. These belong to their respective owners. This API just demonstrates how to build an API that scrapes websites and uses their content.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
// npx vitest run animeAZList.test.ts
|
||||
test("returns az list anime", async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getAZList("0-9", 1);
|
||||
|
||||
expect(data.animes).not.toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { HiAnime } from "aniwatch";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
const animeId = "steinsgate-3";
|
||||
|
||||
// npx vitest run animeAboutInfo.test.ts
|
||||
test(`GET /api/v2/hianime/anime/${animeId}`, async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getInfo(animeId);
|
||||
|
||||
expect(data.anime.info.name).not.toEqual(null);
|
||||
expect(data.recommendedAnimes).not.toEqual([]);
|
||||
expect(data.mostPopularAnimes).not.toEqual([]);
|
||||
expect(Object.keys(data.anime.moreInfo)).not.toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
const category = "subbed-anime";
|
||||
|
||||
// npx vitest run animeCategory.test.ts
|
||||
test(`GET /api/v2/hianime/category/${category}`, async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getCategoryAnime(category);
|
||||
|
||||
expect(data.animes).not.toEqual([]);
|
||||
expect(data.genres).not.toEqual([]);
|
||||
expect(data.top10Animes.today).not.toEqual([]);
|
||||
expect(data.top10Animes.week).not.toEqual([]);
|
||||
expect(data.top10Animes.month).not.toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
const producerName = "toei-animation";
|
||||
const page = 2;
|
||||
|
||||
// npx vitest run animeProducer.test.ts
|
||||
test(`GET /api/v2/hianime/producer/${producerName}?page=${page}`, async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getProducerAnimes(producerName, page);
|
||||
|
||||
expect(data.animes).not.toEqual([]);
|
||||
expect(data.topAiringAnimes).not.toEqual([]);
|
||||
expect(data.top10Animes.today).not.toEqual([]);
|
||||
expect(data.top10Animes.week).not.toEqual([]);
|
||||
expect(data.top10Animes.month).not.toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
const animeId = "one-piece-100";
|
||||
|
||||
// npx vitest run animeQtip.test.ts
|
||||
test(`returns ${animeId} anime qtip info`, async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getQtipInfo(animeId);
|
||||
|
||||
expect(data.anime.id).not.toEqual(null);
|
||||
expect(data.anime.name).not.toEqual(null);
|
||||
expect(data.anime.description).not.toEqual(null);
|
||||
expect(data.anime.genres).not.toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
const animeEpisodeId = "steinsgate-0-92?ep=2055";
|
||||
|
||||
// npx vitest run episodeServers.test.ts
|
||||
test(`GET /api/v2/hianime/episode/servers?animeEpisodeId=${animeEpisodeId}`, async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getEpisodeServers(animeEpisodeId);
|
||||
|
||||
expect(data.episodeId).not.toEqual(null);
|
||||
expect(data.episodeNo).not.toEqual(0);
|
||||
expect(data.sub).not.toEqual([]);
|
||||
expect(data.dub).not.toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
test("GET /api/v2/hianime/home", async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getHomePage();
|
||||
|
||||
expect(data.spotlightAnimes).not.toEqual([]);
|
||||
expect(data.trendingAnimes).not.toEqual([]);
|
||||
expect(data.latestEpisodeAnimes).not.toEqual([]);
|
||||
expect(data.topUpcomingAnimes).not.toEqual([]);
|
||||
expect(data.topAiringAnimes).not.toEqual([]);
|
||||
expect(data.mostPopularAnimes).not.toEqual([]);
|
||||
expect(data.mostFavoriteAnimes).not.toEqual([]);
|
||||
expect(data.latestCompletedAnimes).not.toEqual([]);
|
||||
expect(data.genres).not.toEqual([]);
|
||||
|
||||
expect(data.top10Animes.today).not.toEqual([]);
|
||||
expect(data.top10Animes.week).not.toEqual([]);
|
||||
expect(data.top10Animes.month).not.toEqual([]);
|
||||
});
|
||||
@@ -1,11 +1,20 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
function padZero(num: number) {
|
||||
return num < 10 ? `0${num}` : num.toString();
|
||||
}
|
||||
|
||||
// npx vitest run nextEpisodeSchedule.test.ts
|
||||
test("returns anime next episode schedule", async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
|
||||
const animeId = "one-piece-100";
|
||||
const d = new Date();
|
||||
const scheduleData = await hianime.getEstimatedSchedule(
|
||||
`${d.getFullYear()}-${padZero(d.getMonth() + 1)}-${padZero(d.getDate())}`
|
||||
);
|
||||
|
||||
const animeId = scheduleData.scheduledAnimes[0].id!;
|
||||
const data = await hianime.getNextEpisodeSchedule(animeId);
|
||||
|
||||
expect(data.airingISOTimestamp).not.toEqual(null);
|
||||
+23
-17
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "aniwatch-api",
|
||||
"version": "2.12.0",
|
||||
"description": "Node.js API for obtaining anime information from hianime.to",
|
||||
"description": "Node.js API for obtaining anime information from hianimez.to",
|
||||
"main": "src/server.ts",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -9,11 +9,12 @@
|
||||
"dev": "tsx watch src/server.ts",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"vercel-build": "echo \"Hello\"",
|
||||
"prepare": "husky install",
|
||||
"prepare": "node .husky/install.mjs",
|
||||
"test": "vitest run --config vitest.config.ts",
|
||||
"healthcheck": "curl -f http://localhost:4000/health",
|
||||
"lint": "prettier --cache --write .",
|
||||
"lint:ci": "prettier --cache --check ."
|
||||
"lint": "tsc",
|
||||
"format": "prettier --cache --write .",
|
||||
"format:check": "prettier --cache --check ."
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -26,26 +27,31 @@
|
||||
"keywords": [
|
||||
"anime",
|
||||
"weeb",
|
||||
"hianime",
|
||||
"aniwatch",
|
||||
"scraper"
|
||||
"scraper",
|
||||
"zoro.to",
|
||||
"aniwatch.to",
|
||||
"hianime.to",
|
||||
"hianimez.to"
|
||||
],
|
||||
"author": "https://github.com/ghoshRitesh12",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@hono/node-server": "^1.13.7",
|
||||
"aniwatch": "^2.18.3",
|
||||
"dotenv": "^16.4.7",
|
||||
"hono": "^4.6.15",
|
||||
"@hono/node-server": "^1.14.1",
|
||||
"aniwatch": "^2.22.0",
|
||||
"dotenv": "^16.5.0",
|
||||
"envalid": "^8.0.0",
|
||||
"hono": "^4.7.9",
|
||||
"hono-rate-limiter": "^0.4.2",
|
||||
"ioredis": "^5.4.2"
|
||||
"ioredis": "^5.6.1",
|
||||
"pino": "^9.6.0",
|
||||
"tsx": "^4.19.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.3",
|
||||
"@types/node": "^22.15.17",
|
||||
"husky": "^9.1.7",
|
||||
"prettier": "^3.4.2",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.7.2",
|
||||
"vitest": "^2.1.8"
|
||||
"pino-pretty": "^13.0.0",
|
||||
"prettier": "^3.5.3",
|
||||
"typescript": "^5.8.3",
|
||||
"vitest": "^3.1.3"
|
||||
}
|
||||
}
|
||||
+14
-13
@@ -23,19 +23,18 @@
|
||||
<meta name="twitter:card" content="summary_image">
|
||||
<meta name="twitter:site" content="@aniwatch-api">
|
||||
<meta name="twitter:title" content="Aniwatch API">
|
||||
<meta name="twitter:description" content="Node.js API for obtaining anime information from hianime.to">
|
||||
<meta name="twitter:description" content="Node.js API for obtaining anime information from hianimez.to">
|
||||
<meta name="twitter:image:src"
|
||||
content="https://raw.githubusercontent.com/ghoshRitesh12/aniwatch-api/refs/heads/main/public/img/hianime_v2.png">
|
||||
<meta name="keywords" content="hianime api scraper anime aniwatch node express typescript">
|
||||
<meta property="og:title" content="Aniwatch API">
|
||||
<meta name="description" content="Node.js API for obtaining anime information from hianime.to">
|
||||
<meta property="og:description" content="Node.js API for obtaining anime information from hianime.to">
|
||||
<meta name="description" content="Node.js API for obtaining anime information from hianimez.to">
|
||||
<meta property="og:description" content="Node.js API for obtaining anime information from hianimez.to">
|
||||
<link rel="shortcut icon"
|
||||
href="https://raw.githubusercontent.com/ghoshRitesh12/aniwatch-api/refs/heads/main/public/img/hianime_v2.png">
|
||||
|
||||
<style>
|
||||
* {
|
||||
--accent: #d5b3ff;
|
||||
box-sizing: border-box;
|
||||
font-family: sans-serif;
|
||||
transition:
|
||||
@@ -46,8 +45,10 @@
|
||||
}
|
||||
|
||||
html {
|
||||
color-scheme: dark;
|
||||
--accent: #d5b3ff;
|
||||
|
||||
height: 100%;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
body {
|
||||
@@ -134,7 +135,7 @@
|
||||
right: 0;
|
||||
z-index: 2;
|
||||
|
||||
background: url("https://hianime.to/images/live-thumb.png") repeat;
|
||||
background: url("https://raw.githubusercontent.com/ghoshRitesh12/aniwatch-api/refs/heads/main/public/img/dot.png") repeat;
|
||||
}
|
||||
|
||||
h2 {
|
||||
@@ -203,7 +204,7 @@
|
||||
IMPORTANT:
|
||||
1. The hosted version of this API is only meant to demo the API and would have rate-limiting enabled to minimise bandwidth
|
||||
consumption. It is recommended to deploy your own instance for personal use by customizing the API as you need it to be.
|
||||
2. This API is just an unofficial API for hianime.to and is in no other way officially related to the same.
|
||||
2. This API is just an unofficial API for hianimez.to and is in no other way officially related to the same.
|
||||
3. The content that this API provides is not mine, nor is it hosted by me. These belong to their respective owners. This
|
||||
API just demonstrates how to build an API that scrapes websites and uses their content.
|
||||
-->
|
||||
@@ -216,7 +217,7 @@ API just demonstrates how to build an API that scrapes websites and uses their c
|
||||
<section>
|
||||
<h2>
|
||||
Welcome to the unofficial
|
||||
<a href="https://hianime.to/home" style="text-underline-offset: 3px;">hianime.to</a>
|
||||
<a href="https://hianimez.to/home" style="text-underline-offset: 3px;">hianimez.to</a>
|
||||
API
|
||||
<span style="-webkit-text-fill-color: var(--accent)">⚔️</span>
|
||||
</h2>
|
||||
@@ -231,12 +232,11 @@ API just demonstrates how to build an API that scrapes websites and uses their c
|
||||
decoding="async">
|
||||
</a>
|
||||
<a href="https://github.com/ghoshRitesh12/aniwatch-api/issues?q=is%3Aissue+is%3Aopen+">
|
||||
<img src="https://img.shields.io/github/issues/ghoshRitesh12/aniwatch-api?style=social&logo=github" alt="Issues"
|
||||
decoding="async">
|
||||
<img src="https://img.shields.io/github/issues/ghoshRitesh12/aniwatch-api?style=social&logo=github"
|
||||
alt="Issues" decoding="async">
|
||||
</a>
|
||||
<a href="https://github.com/ghoshRitesh12/aniwatch-api/releases/latest">
|
||||
<img
|
||||
src="https://img.shields.io/github/v/release/ghoshRitesh12/aniwatch-api?display_name=release&style=social&logo=github"
|
||||
<img src="https://img.shields.io/github/v/release/ghoshRitesh12/aniwatch-api?display_name=release&style=social&logo=github"
|
||||
alt="Version" decoding="async">
|
||||
</a>
|
||||
</div>
|
||||
@@ -268,7 +268,8 @@ API just demonstrates how to build an API that scrapes websites and uses their c
|
||||
|
||||
<a href="https://github.com/ghoshRitesh12/aniwatch-api/graphs/contributors"
|
||||
style="display: block; margin-bottom: 1rem; user-select: none;">
|
||||
<img src="https://contrib.rocks/image?repo=ghoshRitesh12/aniwatch-api" alt="Contributors" decoding="async">
|
||||
<img src="https://contrib.rocks/image?repo=ghoshRitesh12/aniwatch-api" alt="Contributors"
|
||||
decoding="async">
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
+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();
|
||||
|
||||
+6
-8
@@ -1,17 +1,15 @@
|
||||
import { config } from "dotenv";
|
||||
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
|
||||
? process.env.ANIWATCH_API_CORS_ALLOWED_ORIGINS.split(",")
|
||||
: ["http://localhost:4000", "*"];
|
||||
const allowedOrigins = env.ANIWATCH_API_CORS_ALLOWED_ORIGINS
|
||||
? env.ANIWATCH_API_CORS_ALLOWED_ORIGINS.split(",")
|
||||
: DEFAULT_ALLOWED_ORIGINS;
|
||||
|
||||
const corsConfig = cors({
|
||||
export const corsConfig = cors({
|
||||
allowMethods: ["GET"],
|
||||
maxAge: 600,
|
||||
credentials: true,
|
||||
origin: allowedOrigins,
|
||||
});
|
||||
|
||||
export default corsConfig;
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { config } from "dotenv";
|
||||
import { cleanEnv, num, str, bool, url, port } from "envalid";
|
||||
|
||||
config();
|
||||
|
||||
export const env = cleanEnv(process.env, {
|
||||
ANIWATCH_API_PORT: port({
|
||||
default: 4000,
|
||||
desc: "Port number of the Aniwatch API.",
|
||||
}),
|
||||
|
||||
ANIWATCH_API_WINDOW_MS: num({
|
||||
// 60 mins if dev, else 30 mins
|
||||
default: isDevEnv() ? 60 * 60 * 1000 : 30 * 60 * 1000,
|
||||
desc: "Duration to track requests for rate limiting (in milliseconds).",
|
||||
docs: "https://github.com/ghoshRitesh12/aniwatch-api/blob/main/.env.example#L9",
|
||||
}),
|
||||
|
||||
ANIWATCH_API_MAX_REQS: num({
|
||||
default: isDevEnv() ? 600 : 6,
|
||||
desc: "Maximum number of requests in the `ANIWATCH_API_WINDOW_MS` time period.",
|
||||
}),
|
||||
|
||||
ANIWATCH_API_CORS_ALLOWED_ORIGINS: str({
|
||||
default: undefined,
|
||||
example:
|
||||
"https://your-production-domain.com,https://another-trusted-domain.com",
|
||||
desc: "Allowed origins, separated by commas and no spaces in between (CSV).",
|
||||
}),
|
||||
|
||||
ANIWATCH_API_VERCEL_DEPLOYMENT: bool({
|
||||
default: false,
|
||||
desc: "Required for distinguishing Vercel deployment from other ones; set it to true",
|
||||
}),
|
||||
|
||||
ANIWATCH_API_HOSTNAME: url({
|
||||
default: undefined,
|
||||
example: "https://your-production-domain.com",
|
||||
desc: "Set this to your api instance's hostname to enable rate limiting, don't have this value if you don't wish to rate limit.",
|
||||
docs: "https://github.com/ghoshRitesh12/aniwatch-api/blob/main/.env.example#L18",
|
||||
}),
|
||||
|
||||
ANIWATCH_API_REDIS_CONN_URL: url({
|
||||
default: undefined,
|
||||
example:
|
||||
"rediss://default:your-secure-password@your-redis-instance-name.provider.com:6379",
|
||||
desc: "This env is optional by default and can be set to utilize Redis caching functionality. It has to be a valid connection URL.",
|
||||
}),
|
||||
|
||||
ANIWATCH_API_S_MAXAGE: num({
|
||||
default: 60,
|
||||
desc: "Specifies the maximum amount of time (in seconds) a resource is considered fresh when served by a CDN cache.",
|
||||
}),
|
||||
|
||||
ANIWATCH_API_STALE_WHILE_REVALIDATE: num({
|
||||
default: 30,
|
||||
desc: "Specifies the amount of time (in seconds) a resource is served stale while a new one is fetched.",
|
||||
}),
|
||||
|
||||
NODE_ENV: str({
|
||||
default: "development",
|
||||
choices: ["development", "production", "test", "staging"],
|
||||
desc: "The environment in which the application is running.",
|
||||
docs: "https://nodejs.org/en/learn/getting-started/nodejs-the-difference-between-development-and-production",
|
||||
}),
|
||||
});
|
||||
|
||||
function isDevEnv(): boolean {
|
||||
return (
|
||||
!process.env.NODE_ENV ||
|
||||
process.env.NODE_ENV === "development" ||
|
||||
process.env.NODE_ENV === "test"
|
||||
);
|
||||
}
|
||||
|
||||
export function isEnvUndefined(envVar?: string): boolean {
|
||||
return typeof envVar === "undefined" || envVar === "undefined";
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { HiAnimeError } from "aniwatch";
|
||||
import type { ErrorHandler, NotFoundHandler } from "hono";
|
||||
import type { ContentfulStatusCode } from "hono/utils/http-status";
|
||||
import { log } from "./logger.js";
|
||||
|
||||
const errResp: { status: ContentfulStatusCode; message: string } = {
|
||||
status: 500,
|
||||
@@ -8,7 +9,7 @@ const errResp: { status: ContentfulStatusCode; message: string } = {
|
||||
};
|
||||
|
||||
export const errorHandler: ErrorHandler = (err, c) => {
|
||||
console.error(err);
|
||||
log.error(JSON.stringify(err));
|
||||
|
||||
if (err instanceof HiAnimeError) {
|
||||
errResp.status = err.status as ContentfulStatusCode;
|
||||
@@ -22,6 +23,6 @@ export const notFoundHandler: NotFoundHandler = (c) => {
|
||||
errResp.status = 404;
|
||||
errResp.message = "Not Found";
|
||||
|
||||
console.error(errResp);
|
||||
log.error(JSON.stringify(errResp));
|
||||
return c.json(errResp, errResp.status);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { env } from "./env.js";
|
||||
import { pino, type LoggerOptions } from "pino";
|
||||
|
||||
const loggerOptions: LoggerOptions = {
|
||||
redact: env.isProduction ? ["hostname"] : [],
|
||||
level: "info",
|
||||
transport: env.isDev
|
||||
? {
|
||||
target: "pino-pretty",
|
||||
options: {
|
||||
colorize: true,
|
||||
translateTime: "SYS:standard",
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
formatters: {
|
||||
level(label) {
|
||||
return {
|
||||
level: label.toUpperCase(),
|
||||
};
|
||||
},
|
||||
},
|
||||
timestamp: pino.stdTimeFunctions.isoTime,
|
||||
};
|
||||
|
||||
export const log = pino(loggerOptions);
|
||||
@@ -1,12 +1,10 @@
|
||||
import { config } from "dotenv";
|
||||
import { rateLimiter } from "hono-rate-limiter";
|
||||
import { getConnInfo } from "@hono/node-server/conninfo";
|
||||
|
||||
config();
|
||||
import { env } from "./env.js";
|
||||
|
||||
export const ratelimit = rateLimiter({
|
||||
windowMs: Number(process.env.ANIWATCH_API_WINDOW_MS) || 30 * 60 * 1000,
|
||||
limit: Number(process.env.ANIWATCH_API_MAX_REQS) || 6,
|
||||
windowMs: env.ANIWATCH_API_WINDOW_MS,
|
||||
limit: env.ANIWATCH_API_MAX_REQS,
|
||||
standardHeaders: "draft-7",
|
||||
keyGenerator(c) {
|
||||
const { remote } = getConnInfo(c);
|
||||
@@ -17,5 +15,8 @@ export const ratelimit = rateLimiter({
|
||||
return key;
|
||||
},
|
||||
handler: (c) =>
|
||||
c.json({ status: 429, message: "Too Many Requests 😵" }, { status: 429 }),
|
||||
c.json(
|
||||
{ status: 429, message: "Too Many Requests 😵" },
|
||||
{ status: 429 }
|
||||
),
|
||||
});
|
||||
|
||||
@@ -5,4 +5,4 @@ type CacheVariables = {
|
||||
};
|
||||
};
|
||||
|
||||
export type AniwatchAPIVariables = {} & CacheVariables;
|
||||
export type AniwatchAPIVariables = CacheVariables & {};
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { config } from "dotenv";
|
||||
import { AniwatchAPICache } from "../config/cache.js";
|
||||
import type { MiddlewareHandler } from "hono";
|
||||
|
||||
config();
|
||||
import { env } from "../config/env.js";
|
||||
import { AniwatchAPICache } from "../config/cache.js";
|
||||
|
||||
// Define middleware to add Cache-Control header
|
||||
export const cacheControlMiddleware: MiddlewareHandler = async (c, next) => {
|
||||
const sMaxAge = process.env.ANIWATCH_API_S_MAXAGE || "60";
|
||||
const staleWhileRevalidate =
|
||||
process.env.ANIWATCH_API_STALE_WHILE_REVALIDATE || "30";
|
||||
export const cacheControl: MiddlewareHandler = async (c, next) => {
|
||||
const sMaxAge = env.ANIWATCH_API_S_MAXAGE;
|
||||
const staleWhileRevalidate = env.ANIWATCH_API_STALE_WHILE_REVALIDATE;
|
||||
|
||||
c.header(
|
||||
"Cache-Control",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { MiddlewareHandler } from "hono";
|
||||
import { logger as honoLogger } from "hono/logger";
|
||||
import { log } from "../config/logger.js";
|
||||
|
||||
export const logging: MiddlewareHandler = honoLogger(
|
||||
(msg: string, ...rest: string[]) => {
|
||||
log.info(msg, ...rest);
|
||||
}
|
||||
);
|
||||
+27
-34
@@ -1,40 +1,36 @@
|
||||
import https from "https";
|
||||
import { config } from "dotenv";
|
||||
|
||||
import corsConfig from "./config/cors.js";
|
||||
import { ratelimit } from "./config/ratelimit.js";
|
||||
|
||||
import {
|
||||
cacheConfigSetter,
|
||||
cacheControlMiddleware,
|
||||
} from "./middleware/cache.js";
|
||||
import { hianimeRouter } from "./routes/hianime.js";
|
||||
|
||||
import { Hono } from "hono";
|
||||
import { logger } from "hono/logger";
|
||||
import { serve } from "@hono/node-server";
|
||||
import { serveStatic } from "@hono/node-server/serve-static";
|
||||
|
||||
import pkgJson from "../package.json" with { type: "json" };
|
||||
import { env } from "./config/env.js";
|
||||
import { log } from "./config/logger.js";
|
||||
import { corsConfig } from "./config/cors.js";
|
||||
import { ratelimit } from "./config/ratelimit.js";
|
||||
import { errorHandler, notFoundHandler } from "./config/errorHandler.js";
|
||||
import type { AniwatchAPIVariables } from "./config/variables.js";
|
||||
|
||||
config();
|
||||
import { hianimeRouter } from "./routes/hianime.js";
|
||||
import { logging } from "./middleware/logging.js";
|
||||
import { cacheConfigSetter, cacheControl } from "./middleware/cache.js";
|
||||
|
||||
import pkgJson from "../package.json" with { type: "json" };
|
||||
|
||||
//
|
||||
const BASE_PATH = "/api/v2" as const;
|
||||
const PORT: number = Number(process.env.ANIWATCH_API_PORT) || 4000;
|
||||
const ANIWATCH_API_HOSTNAME = process.env?.ANIWATCH_API_HOSTNAME;
|
||||
|
||||
const app = new Hono<{ Variables: AniwatchAPIVariables }>();
|
||||
|
||||
app.use(logger());
|
||||
app.use(logging);
|
||||
app.use(corsConfig);
|
||||
app.use(cacheControlMiddleware);
|
||||
app.use(cacheControl);
|
||||
|
||||
//
|
||||
// CAUTION: For personal deployments, "refrain" from having an env
|
||||
// named "ANIWATCH_API_HOSTNAME". You may face rate limitting
|
||||
// or other issues if you do.
|
||||
const ISNT_PERSONAL_DEPLOYMENT = Boolean(ANIWATCH_API_HOSTNAME);
|
||||
const ISNT_PERSONAL_DEPLOYMENT = Boolean(env.ANIWATCH_API_HOSTNAME);
|
||||
if (ISNT_PERSONAL_DEPLOYMENT) {
|
||||
app.use(ratelimit);
|
||||
}
|
||||
@@ -43,7 +39,8 @@ app.use("/", serveStatic({ root: "public" }));
|
||||
app.get("/health", (c) => c.text("daijoubu", { status: 200 }));
|
||||
app.get("/v", async (c) =>
|
||||
c.text(
|
||||
`v${"version" in pkgJson && pkgJson?.version ? pkgJson.version : "-1"}`
|
||||
`aniwatch-api: v${"version" in pkgJson && pkgJson?.version ? pkgJson.version : "-1"}\n` +
|
||||
`aniwatch-package: v${"dependencies" in pkgJson && pkgJson?.dependencies?.aniwatch ? pkgJson?.dependencies?.aniwatch : "-1"}`
|
||||
)
|
||||
);
|
||||
|
||||
@@ -57,18 +54,17 @@ app.basePath(BASE_PATH).get("/anicrush", (c) =>
|
||||
app.notFound(notFoundHandler);
|
||||
app.onError(errorHandler);
|
||||
|
||||
//
|
||||
// NOTE: this env is "required" for vercel deployments
|
||||
if (!Boolean(process.env?.ANIWATCH_API_VERCEL_DEPLOYMENT)) {
|
||||
if (!env.ANIWATCH_API_VERCEL_DEPLOYMENT) {
|
||||
serve({
|
||||
port: PORT,
|
||||
port: env.ANIWATCH_API_PORT,
|
||||
fetch: app.fetch,
|
||||
}).addListener("listening", () =>
|
||||
console.info(
|
||||
"\x1b[1;36m" +
|
||||
`aniwatch-api at http://localhost:${PORT}` +
|
||||
"\x1b[0m"
|
||||
)
|
||||
}).addListener("listening", () => {
|
||||
log.info(
|
||||
`aniwatch-api RUNNING at http://localhost:${env.ANIWATCH_API_PORT}`
|
||||
);
|
||||
});
|
||||
|
||||
// NOTE: remove the `if` block below for personal deployments
|
||||
if (ISNT_PERSONAL_DEPLOYMENT) {
|
||||
@@ -76,15 +72,12 @@ if (!Boolean(process.env?.ANIWATCH_API_VERCEL_DEPLOYMENT)) {
|
||||
|
||||
// don't sleep
|
||||
setInterval(() => {
|
||||
console.log(
|
||||
"aniwatch-api HEALTH_CHECK at",
|
||||
new Date().toISOString()
|
||||
log.info(
|
||||
`aniwatch-api HEALTH_CHECK at ${new Date().toISOString()}`
|
||||
);
|
||||
https
|
||||
.get(`https://${ANIWATCH_API_HOSTNAME}/health`)
|
||||
.on("error", (err) => {
|
||||
console.error(err.message);
|
||||
});
|
||||
.get(`https://${env.ANIWATCH_API_HOSTNAME}/health`)
|
||||
.on("error", (err) => log.error(err.message.trim()));
|
||||
}, interval);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import { HiAnime } from "aniwatch";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
const animeId = "steinsgate-3";
|
||||
|
||||
// npx vitest run animeAboutInfo.test.ts
|
||||
test(`GET /api/v2/hianime/anime/${animeId}`, async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getInfo(animeId);
|
||||
|
||||
expect(data.anime.info.name).not.toEqual(null);
|
||||
expect(data.recommendedAnimes).not.toEqual([]);
|
||||
expect(data.mostPopularAnimes).not.toEqual([]);
|
||||
expect(Object.keys(data.anime.moreInfo)).not.toEqual([]);
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
const category = "subbed-anime";
|
||||
|
||||
// npx vitest run animeCategory.test.ts
|
||||
test(`GET /api/v2/hianime/category/${category}`, async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getCategoryAnime(category);
|
||||
|
||||
expect(data.animes).not.toEqual([]);
|
||||
expect(data.genres).not.toEqual([]);
|
||||
expect(data.top10Animes.today).not.toEqual([]);
|
||||
expect(data.top10Animes.week).not.toEqual([]);
|
||||
expect(data.top10Animes.month).not.toEqual([]);
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
const producerName = "toei-animation";
|
||||
const page = 2;
|
||||
|
||||
// npx vitest run animeProducer.test.ts
|
||||
test(`GET /api/v2/hianime/producer/${producerName}?page=${page}`, async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getProducerAnimes(producerName, page);
|
||||
|
||||
expect(data.animes).not.toEqual([]);
|
||||
expect(data.topAiringAnimes).not.toEqual([]);
|
||||
expect(data.top10Animes.today).not.toEqual([]);
|
||||
expect(data.top10Animes.week).not.toEqual([]);
|
||||
expect(data.top10Animes.month).not.toEqual([]);
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
const animeEpisodeId = "steinsgate-0-92?ep=2055";
|
||||
|
||||
// npx vitest run episodeServers.test.ts
|
||||
test(`GET /api/v2/hianime/episode/servers?animeEpisodeId=${animeEpisodeId}`, async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getEpisodeServers(animeEpisodeId);
|
||||
|
||||
expect(data.episodeId).not.toEqual(null);
|
||||
expect(data.episodeNo).not.toEqual(0);
|
||||
expect(data.sub).not.toEqual([]);
|
||||
expect(data.dub).not.toEqual([]);
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { HiAnime } from "aniwatch";
|
||||
|
||||
test("GET /api/v2/hianime/home", async () => {
|
||||
const hianime = new HiAnime.Scraper();
|
||||
const data = await hianime.getHomePage();
|
||||
|
||||
expect(data.spotlightAnimes).not.toEqual([]);
|
||||
expect(data.trendingAnimes).not.toEqual([]);
|
||||
expect(data.latestEpisodeAnimes).not.toEqual([]);
|
||||
expect(data.topUpcomingAnimes).not.toEqual([]);
|
||||
expect(data.topAiringAnimes).not.toEqual([]);
|
||||
expect(data.mostPopularAnimes).not.toEqual([]);
|
||||
expect(data.mostFavoriteAnimes).not.toEqual([]);
|
||||
expect(data.latestCompletedAnimes).not.toEqual([]);
|
||||
expect(data.genres).not.toEqual([]);
|
||||
|
||||
expect(data.top10Animes.today).not.toEqual([]);
|
||||
expect(data.top10Animes.week).not.toEqual([]);
|
||||
expect(data.top10Animes.month).not.toEqual([]);
|
||||
});
|
||||
Reference in New Issue
Block a user