feat: render search on server
This commit is contained in:
@@ -2,7 +2,7 @@ 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";
|
||||
import { parseResourceUrl, searchResource } from "@lib/search.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(req, ctx) {
|
||||
@@ -11,52 +11,10 @@ export const handler: Handlers = {
|
||||
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(" && ") });
|
||||
const searchParams = parseResourceUrl(req.url);
|
||||
|
||||
// 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,
|
||||
});
|
||||
const searchResults = await searchResource(searchParams);
|
||||
|
||||
return json(searchResults);
|
||||
},
|
||||
|
Reference in New Issue
Block a user