feat: add redis cache (#231)

* feat: add redis cache

* chore: add TTL

* chore: change port
This commit is contained in:
Alexandro Castro 2023-10-03 16:38:18 +01:00 • committed by GitHub
parent dc043fbe78
commit 614e0453d0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 124 additions and 10 deletions

View file

@ -5,6 +5,7 @@
- Deno >= v1.36.1 - Deno >= v1.36.1
- [Vercel](https://vercel.com/) - [Vercel](https://vercel.com/)
- GitHub API v4 - GitHub API v4
- Docker and Docker compose (optional)
## Local Run ## Local Run
@ -26,6 +27,14 @@ Run local server.
deno task start 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. Open localhost from your browser.
http://localhost:8080/?username=ryo-ma http://localhost:8080/?username=ryo-ma

View file

@ -8,6 +8,7 @@ import { GithubRepositoryService } from "../src/Repository/GithubRepository.ts";
import { GithubApiService } from "../src/Services/GithubApiService.ts"; import { GithubApiService } from "../src/Services/GithubApiService.ts";
import { ServiceError } from "../src/Types/index.ts"; import { ServiceError } from "../src/Types/index.ts";
import { ErrorPage } from "../src/pages/Error.ts"; import { ErrorPage } from "../src/pages/Error.ts";
import { cacheProvider } from "../src/config/cache.ts";
const serviceProvider = new GithubApiService(); const serviceProvider = new GithubApiService();
const client = new GithubRepositoryService(serviceProvider).repository; const client = new GithubRepositoryService(serviceProvider).repository;
@ -75,17 +76,25 @@ async function app(req: Request): Promise<Response> {
}, },
); );
} }
const userInfo = await client.requestUserInfo(username); const userKeyCache = ["v1", username].join("-");
if (userInfo instanceof ServiceError) { const userInfoCached = await cacheProvider.get(userKeyCache) || "{}";
return new Response( let userInfo = JSON.parse(userInfoCached);
ErrorPage({ error: userInfo, username }).render(), const hasCache = !!Object.keys(userInfo).length;
{
status: userInfo.code,
headers: new Headers({ "Content-Type": "text" }),
},
);
}
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 // Success Response
return new Response( return new Response(
new Card( new Card(

View file

@ -11,6 +11,12 @@ import {
stub, stub,
} from "https://deno.land/std@0.203.0/testing/mock.ts"; } 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"; import { CONSTANTS } from "./src/utils.ts";
const baseURL = Deno.env.get("GITHUB_API") || CONSTANTS.DEFAULT_GITHUB_API; const baseURL = Deno.env.get("GITHUB_API") || CONSTANTS.DEFAULT_GITHUB_API;

7
docker-compose.yml Normal file
View file

@ -0,0 +1,7 @@
version: "3"
services:
redis:
container_name: trophy-redis
image: redis:latest
ports:
- "6379:6379"

8
env-example Normal file
View file

@ -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=

74
src/config/cache.ts Normal file
View file

@ -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<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") || "",
password: Deno.env.get("REDIS_PASSWORD") || "",
});
}
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();

View file

@ -67,6 +67,7 @@ export const CONSTANTS = {
DEFAULT_GITHUB_API: "https://api.github.com/graphql", DEFAULT_GITHUB_API: "https://api.github.com/graphql",
DEFAULT_GITHUB_RETRY_DELAY: 1000, DEFAULT_GITHUB_RETRY_DELAY: 1000,
REVALIDATE_TIME: HOUR_IN_MILLISECONDS, REVALIDATE_TIME: HOUR_IN_MILLISECONDS,
REDIS_TTL: HOUR_IN_MILLISECONDS * 4,
}; };
export enum RANK { export enum RANK {