memorium/routes/api/resources.ts

64 lines
1.8 KiB
TypeScript

import { Handlers } from "$fresh/server.ts";
import { AccessDeniedError, BadRequestError } from "@lib/errors.ts";
import { getTypeSenseClient } from "@lib/typesense.ts";
import { json } from "@lib/helpers.ts";
import { extractHashTags } from "@lib/string.ts";
export const handler: Handlers = {
async GET(req, ctx) {
const session = ctx.state.session;
if (!session) {
throw new AccessDeniedError();
}
const url = new URL(req.url);
let query = url.searchParams.get("q");
if (!query) {
throw new BadRequestError('Query parameter "q" is required.');
}
query = decodeURIComponent(query);
const query_by = url.searchParams.get("query_by") ||
"name,description,author,tags";
const filter_by: string[] = [];
const type = url.searchParams.get("type");
if (type) {
filter_by.push(`type:=${type}`);
}
const status = url.searchParams.get("status");
if (status) {
filter_by.push(`status:=${status}`);
}
const hashTags = extractHashTags(query);
if (hashTags?.length) {
filter_by.push(`tags:[${hashTags.map((t) => `\`${t}\``).join(",")}]`);
for (const tag of hashTags) {
query = query.replaceAll(`#${tag}`, "");
}
}
const typesenseClient = await getTypeSenseClient();
if (!typesenseClient) {
throw new Error("Query not available");
}
console.log({ query, query_by, filter_by: filter_by.join(" && ") });
// Perform the Typesense search
const searchResults = await typesenseClient.collections("resources")
.documents().search({
q: query,
query_by,
facet_by: "rating,author,tags",
max_facet_values: 10,
filter_by: filter_by.join(" && "),
per_page: 50,
});
return json(searchResults);
},
};