54 lines
1.5 KiB
TypeScript
54 lines
1.5 KiB
TypeScript
import { Handlers } from "$fresh/server.ts";
|
|
import { 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 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 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);
|
|
},
|
|
};
|