48 lines
1011 B
TypeScript
48 lines
1011 B
TypeScript
|
import { HandlerContext } from "$fresh/server.ts";
|
||
|
import { getMovie } from "@lib/tmdb.ts";
|
||
|
import * as cache from "@lib/cache/cache.ts";
|
||
|
|
||
|
type CachedMovieCredits = {
|
||
|
lastUpdated: number;
|
||
|
data: unknown;
|
||
|
};
|
||
|
|
||
|
const CACHE_INTERVAL = 1000 * 60 * 24 * 30;
|
||
|
|
||
|
export const handler = async (
|
||
|
_req: Request,
|
||
|
_ctx: HandlerContext,
|
||
|
) => {
|
||
|
const id = _ctx.params.id;
|
||
|
|
||
|
if (!id) {
|
||
|
return new Response("Bad Request", {
|
||
|
status: 400,
|
||
|
});
|
||
|
}
|
||
|
|
||
|
const headers = new Headers();
|
||
|
headers.append("Content-Type", "application/json");
|
||
|
|
||
|
const cacheId = `/movie/${id}`;
|
||
|
|
||
|
const cachedResponse = await cache.get<CachedMovieCredits>(cacheId);
|
||
|
if (
|
||
|
cachedResponse && Date.now() < (cachedResponse.lastUpdated + CACHE_INTERVAL)
|
||
|
) {
|
||
|
return new Response(JSON.stringify(cachedResponse.data), { headers });
|
||
|
}
|
||
|
|
||
|
const res = await getMovie(+id);
|
||
|
|
||
|
cache.set(
|
||
|
cacheId,
|
||
|
JSON.stringify({
|
||
|
lastUpdated: Date.now(),
|
||
|
data: res,
|
||
|
}),
|
||
|
);
|
||
|
|
||
|
return new Response(JSON.stringify(res));
|
||
|
};
|