diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f5576ac..7306a08 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,6 +5,7 @@ - Deno >= v1.36.1 - [Vercel](https://vercel.com/) - GitHub API v4 +- Docker and Docker compose (optional) ## Local Run @@ -26,6 +27,14 @@ Run local server. deno task start ``` +You can enable the Redis if you want, but it's not mandatory. + +```sh +docker compose up -d +``` + +Rename `env-example` to `.env`, and change ENABLE_REDIS to true + Open localhost from your browser. http://localhost:8080/?username=ryo-ma diff --git a/api/index.ts b/api/index.ts index 68d5215..059fdeb 100644 --- a/api/index.ts +++ b/api/index.ts @@ -8,6 +8,7 @@ import { GithubRepositoryService } from "../src/Repository/GithubRepository.ts"; import { GithubApiService } from "../src/Services/GithubApiService.ts"; import { ServiceError } from "../src/Types/index.ts"; import { ErrorPage } from "../src/pages/Error.ts"; +import { cacheProvider } from "../src/config/cache.ts"; const serviceProvider = new GithubApiService(); const client = new GithubRepositoryService(serviceProvider).repository; @@ -75,17 +76,25 @@ async function app(req: Request): Promise { }, ); } - const userInfo = await client.requestUserInfo(username); - if (userInfo instanceof ServiceError) { - return new Response( - ErrorPage({ error: userInfo, username }).render(), - { - status: userInfo.code, - headers: new Headers({ "Content-Type": "text" }), - }, - ); - } + const userKeyCache = ["v1", username].join("-"); + const userInfoCached = await cacheProvider.get(userKeyCache) || "{}"; + let userInfo = JSON.parse(userInfoCached); + const hasCache = !!Object.keys(userInfo).length; + if (!hasCache) { + const userResponseInfo = await client.requestUserInfo(username); + if (userResponseInfo instanceof ServiceError) { + return new Response( + ErrorPage({ error: userInfo, username }).render(), + { + status: userResponseInfo.code, + headers: new Headers({ "Content-Type": "text" }), + }, + ); + } + userInfo = userResponseInfo; + await cacheProvider.set(userKeyCache, JSON.stringify(userInfo)); + } // Success Response return new Response( new Card( diff --git a/deps.ts b/deps.ts index 691ef99..646eaf2 100644 --- a/deps.ts +++ b/deps.ts @@ -11,6 +11,12 @@ import { stub, } from "https://deno.land/std@0.203.0/testing/mock.ts"; +export { + type Bulk, + connect, + type Redis, +} from "https://deno.land/x/redis@v0.31.0/mod.ts"; + import { CONSTANTS } from "./src/utils.ts"; const baseURL = Deno.env.get("GITHUB_API") || CONSTANTS.DEFAULT_GITHUB_API; diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..9036241 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,7 @@ +version: "3" +services: + redis: + container_name: trophy-redis + image: redis:latest + ports: + - "6379:6379" diff --git a/env-example b/env-example new file mode 100644 index 0000000..6f5a02b --- /dev/null +++ b/env-example @@ -0,0 +1,8 @@ +GITHUB_TOKEN1= +GITHUB_TOKEN2= +GITHUB_API=https://api.github.com/graphql +ENABLE_REDIS= +REDIS_PORT=6379 +REDIS_HOST= +REDIS_USERNAME= +REDIS_PASSWORD= diff --git a/src/config/cache.ts b/src/config/cache.ts new file mode 100644 index 0000000..4f6aef3 --- /dev/null +++ b/src/config/cache.ts @@ -0,0 +1,74 @@ +import { Bulk, connect, Redis } from "../../deps.ts"; +import { Logger } from "../Helpers/Logger.ts"; +import { CONSTANTS } from "../utils.ts"; + +const enableCache = Deno.env.get("ENABLE_REDIS") || false; + +// 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 { + 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") || "", + password: Deno.env.get("REDIS_PASSWORD") || "", + }); + } + + async get(key: string): Promise { + 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 { + 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 { + 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(); diff --git a/src/utils.ts b/src/utils.ts index a3e21fa..a244d11 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -67,6 +67,7 @@ export const CONSTANTS = { DEFAULT_GITHUB_API: "https://api.github.com/graphql", DEFAULT_GITHUB_RETRY_DELAY: 1000, REVALIDATE_TIME: HOUR_IN_MILLISECONDS, + REDIS_TTL: HOUR_IN_MILLISECONDS * 4, }; export enum RANK {