memorium/routes/api/tmdb/query.ts

60 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-08-01 17:50:00 +02:00
import { HandlerContext, Handlers } from "$fresh/server.ts";
2023-08-08 11:03:20 +02:00
import { searchMovie, searchTVShow } from "@lib/tmdb.ts";
2023-07-31 04:19:04 +02:00
import * as cache from "@lib/cache/cache.ts";
2023-08-04 22:35:25 +02:00
import { AccessDeniedError, BadRequestError } from "@lib/errors.ts";
2023-08-01 17:50:00 +02:00
import { json } from "@lib/helpers.ts";
2023-07-31 04:19:04 +02:00
type CachedMovieQuery = {
lastUpdated: number;
data: unknown;
};
const CACHE_INTERVAL = 1000 * 60 * 24 * 30;
2023-08-01 17:50:00 +02:00
const GET = async (
2023-08-04 22:35:25 +02:00
req: Request,
ctx: HandlerContext,
2023-07-31 04:19:04 +02:00
) => {
2023-08-04 22:35:25 +02:00
const session = ctx.state.session;
if (!session) {
throw new AccessDeniedError();
}
const u = new URL(req.url);
2023-07-31 04:19:04 +02:00
const query = u.searchParams.get("q");
if (!query) {
2023-08-01 17:50:00 +02:00
throw new BadRequestError();
2023-07-31 04:19:04 +02:00
}
2023-08-08 11:03:20 +02:00
const type = u.searchParams.get("type") || "movie";
const cacheId = `/${type}/query/${query}`;
2023-07-31 04:19:04 +02:00
const cachedResponse = await cache.get<CachedMovieQuery>(cacheId);
if (
cachedResponse && Date.now() < (cachedResponse.lastUpdated + CACHE_INTERVAL)
) {
2023-08-01 17:50:00 +02:00
return json(cachedResponse.data);
2023-07-31 04:19:04 +02:00
}
2023-08-08 11:03:20 +02:00
const res = type === "movie"
? await searchMovie(query)
: await searchTVShow(query);
2023-07-31 04:19:04 +02:00
cache.set(
cacheId,
JSON.stringify({
lastUpdated: Date.now(),
data: res,
}),
);
return new Response(JSON.stringify(res.results));
};
2023-08-01 17:50:00 +02:00
export const handler: Handlers = {
GET,
};