memorium/routes/api/resources.ts

46 lines
1.2 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);
const query = url.searchParams.get("q");
if (!query) {
throw new BadRequestError('Query parameter "q" is required.');
}
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-06 00:33:06 +02:00
let filter_by = "";
const type = url.searchParams.get("type");
if (type) {
filter_by = `type:=${type}`;
}
2023-08-07 13:42:00 +02:00
const hashTags = extractHashTags(query);
if (hashTags?.length) {
//filter_by += `tags:=${}`
}
2023-08-05 21:52:43 +02:00
const typesenseClient = await getTypeSenseClient();
if (!typesenseClient) {
throw new Error("Query not available");
}
// Perform the Typesense search
const searchResults = await typesenseClient.collections("resources")
.documents().search({
q: query,
query_by,
2023-08-06 00:33:06 +02:00
filter_by,
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
},
};