Skip to content

Commit

Permalink
feat: cache detail
Browse files Browse the repository at this point in the history
  • Loading branch information
yjl9903 committed Apr 24, 2023
1 parent 19b30be commit ce24245
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 2 deletions.
13 changes: 11 additions & 2 deletions packages/worker/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,21 @@ import { fetchDmhyDetail } from 'animegarden';
import type { Env } from './types';

import { makePrisma } from './prisma';
import { getRefreshTimestamp } from './state';
import { makeErrorResponse, makeResponse } from './utils';
import { getDetailStore, getRefreshTimestamp } from './state';

export async function queryResourceDetail(request: IRequest, _req: Request, _env: Env) {
export async function queryResourceDetail(request: IRequest, _req: Request, env: Env) {
const store = getDetailStore(env);
const href = request.params.href;

const cache = await store.get(href);
if (!!cache) {
return makeResponse({ detail: cache });
}

const detail = await fetchDmhyDetail(fetch, href);
await store.put(href, detail);

return makeResponse({ detail });
}

Expand Down
55 changes: 55 additions & 0 deletions packages/worker/src/state.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { ResourceDetail } from 'animegarden';

import type { Env } from './types';

export async function updateRefreshTimestamp(env: Env) {
Expand All @@ -7,3 +9,56 @@ export async function updateRefreshTimestamp(env: Env) {
export async function getRefreshTimestamp(env: Env) {
return new Date((await env.animegarden.get('state/refresh-timestamp')) ?? 0);
}

export function getDetailStore(env: Env) {
return new KVStore<ResourceDetail>(env.animegarden, 'detail/');
}

export class KVStore<V> {
private readonly prefix: string;

constructor(private readonly store: KVNamespace, prefix = '') {
this.prefix = prefix + ':';
}

async get(key: string): Promise<V | undefined> {
const now = new Date();
try {
const text = await this.store.get(this.prefix + key);
if (!!text) {
const result = JSON.parse(text);
const created = new Date(result.timestamp);
if (now.getTime() - created.getTime() <= 1000 * 60 * 60 * 24) {
return result.value;
} else {
await this.remove(key);
return undefined;
}
} else {
return undefined;
}
} catch (error) {
console.error(error);
return undefined;
}
}

async keys(): Promise<string[]> {
return (await this.store.list({ prefix: this.prefix })).keys.map((k) => k.name);
}

async has(key: string): Promise<boolean> {
return !!(await this.store.get(this.prefix + key));
}

async put(key: string, value: V): Promise<void> {
await this.store.put(
this.prefix + key,
JSON.stringify({ timestamp: new Date().toISOString(), value })
);
}

async remove(key: string): Promise<void> {
await this.store.delete(this.prefix + key);
}
}

0 comments on commit ce24245

Please sign in to comment.