memorium/routes/api/resources.ts

59 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-08-05 21:52:43 +02:00
import { Handlers } from "$fresh/server.ts";
import { BadRequestError } from "@lib/errors.ts";
import { getTypeSenseClient } from "@lib/typesense.ts";
import { json } from "@lib/helpers.ts";
2023-08-07 13:42:00 +02:00
import { extractHashTags } from "@lib/string.ts";
2023-08-05 21:52:43 +02:00
export const handler: Handlers = {
async GET(req, _ctx) {
const url = new URL(req.url);
2023-08-08 21:50:23 +02:00
let query = url.searchParams.get("q");
2023-08-05 21:52:43 +02:00
if (!query) {
throw new BadRequestError('Query parameter "q" is required.');
}
2023-08-08 21:50:23 +02:00
query = decodeURIComponent(query);
2023-08-05 21:52:43 +02:00
2023-08-08 11:03:20 +02:00
const query_by = url.searchParams.get("query_by") ||
"name,description,author,tags";
2023-08-05 21:52:43 +02:00
2023-08-08 21:50:23 +02:00
const filter_by: string[] = [];
2023-08-06 00:33:06 +02:00
const type = url.searchParams.get("type");
if (type) {
2023-08-08 21:50:23 +02:00
filter_by.push(`type:=${type}`);
2023-08-06 00:33:06 +02:00
}
2023-08-09 13:32:28 +02:00
const status = url.searchParams.get("status");
if (status) {
filter_by.push(`status:=${status}`);
}
2023-08-07 13:42:00 +02:00
const hashTags = extractHashTags(query);
if (hashTags?.length) {
2023-08-08 21:50:23 +02:00
filter_by.push(`tags:[${hashTags.map((t) => `\`${t}\``).join(",")}]`);
for (const tag of hashTags) {
query = query.replaceAll(`#${tag}`, "");
}
2023-08-07 13:42:00 +02:00
}
2023-08-05 21:52:43 +02:00
const typesenseClient = await getTypeSenseClient();
if (!typesenseClient) {
throw new Error("Query not available");
}
2023-08-08 21:50:23 +02:00
console.log({ query, query_by, filter_by: filter_by.join(" && ") });
2023-08-05 21:52:43 +02:00
// Perform the Typesense search
const searchResults = await typesenseClient.collections("resources")
.documents().search({
q: query,
query_by,
2023-08-08 21:50:23 +02:00
facet_by: "rating,author,tags",
max_facet_values: 10,
filter_by: filter_by.join(" && "),
2023-08-06 17:47:26 +02:00
per_page: 50,
2023-08-05 21:52:43 +02:00
});
2023-08-06 17:47:26 +02:00
return json(searchResults);
2023-08-05 21:52:43 +02:00
},
};