56 lines
1.1 KiB
TypeScript
56 lines
1.1 KiB
TypeScript
import { HandlerContext, Handlers } from "$fresh/server.ts";
|
|
import { searchMovie } from "@lib/tmdb.ts";
|
|
import * as cache from "@lib/cache/cache.ts";
|
|
import { AccessDeniedError, BadRequestError } from "@lib/errors.ts";
|
|
import { json } from "@lib/helpers.ts";
|
|
|
|
type CachedMovieQuery = {
|
|
lastUpdated: number;
|
|
data: unknown;
|
|
};
|
|
|
|
const CACHE_INTERVAL = 1000 * 60 * 24 * 30;
|
|
|
|
const GET = async (
|
|
req: Request,
|
|
ctx: HandlerContext,
|
|
) => {
|
|
const session = ctx.state.session;
|
|
if (!session) {
|
|
throw new AccessDeniedError();
|
|
}
|
|
|
|
const u = new URL(req.url);
|
|
|
|
const query = u.searchParams.get("q");
|
|
|
|
if (!query) {
|
|
throw new BadRequestError();
|
|
}
|
|
|
|
const cacheId = `/movie/query/${query}`;
|
|
|
|
const cachedResponse = await cache.get<CachedMovieQuery>(cacheId);
|
|
if (
|
|
cachedResponse && Date.now() < (cachedResponse.lastUpdated + CACHE_INTERVAL)
|
|
) {
|
|
return json(cachedResponse.data);
|
|
}
|
|
|
|
const res = await searchMovie(query);
|
|
|
|
cache.set(
|
|
cacheId,
|
|
JSON.stringify({
|
|
lastUpdated: Date.now(),
|
|
data: res,
|
|
}),
|
|
);
|
|
|
|
return new Response(JSON.stringify(res.results));
|
|
};
|
|
|
|
export const handler: Handlers = {
|
|
GET,
|
|
};
|