diff --git a/meilisearch/sdk.ts b/meilisearch/sdk.ts new file mode 100644 index 0000000..8a1c5d5 --- /dev/null +++ b/meilisearch/sdk.ts @@ -0,0 +1,42 @@ +import { MeiliDocument, SearchRequest, SearchResponse } from "./types"; + +export class MeilisearchSDK { + constructor( + private readonly apiURL: string, + private readonly bearer: string + ) {} + + async search({ + q, + page, + types, + }: SearchRequest): Promise> { + const filter: string[] = []; + + if (types) { + if (typeof types === "string") { + filter.push(`type = ${types}`); + } else { + filter.push(`type IN [${types.join(", ")}]`); + } + } + + const body = { + q, + page, + hitsPerPage: 25, + filter, + sort: ["updatedAt:desc"], + }; + + const result = await fetch(`${this.apiURL}/indexes/DOCUMENT/search`, { + method: "POST", + body: JSON.stringify(body), + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.bearer}`, + }, + }); + return await result.json(); + } +} diff --git a/meilisearch/types.ts b/meilisearch/types.ts new file mode 100644 index 0000000..12c732c --- /dev/null +++ b/meilisearch/types.ts @@ -0,0 +1,77 @@ +import { Collections } from "../payload/constants"; +import { + EndpointCollectible, + EndpointPage, + EndpointFolder, + EndpointVideo, + EndpointAudio, + EndpointImage, + EndpointFile, + EndpointRecorder, + EndpointChronologyEvent, +} from "../payload/endpoint-types"; + +export type MeiliDocument = { + meilid: string; + id: string; + languages: string[]; + title?: string; + content?: string; +} & ( + | { + type: Collections.Collectibles; + data: EndpointCollectible; + } + | { + type: Collections.Pages; + data: EndpointPage; + } + | { + type: Collections.Folders; + data: EndpointFolder; + } + | { + type: Collections.Videos; + data: EndpointVideo; + } + | { + type: Collections.Audios; + data: EndpointAudio; + } + | { + type: Collections.Images; + data: EndpointImage; + } + | { + type: Collections.Files; + data: EndpointFile; + } + | { + type: Collections.Recorders; + data: EndpointRecorder; + } + | { + type: Collections.ChronologyEvents; + data: { + date: EndpointChronologyEvent["date"]; + event: EndpointChronologyEvent["events"][number]; + }; + } +); + +export type SearchResponse = { + hits: T[]; + query: string; + processingTimeMs: number; + hitsPerPage: number; + page: number; + totalPages: number; + totalHits: number; + facetDistribution: Record<"type" | "languages", Record>; +}; + +export type SearchRequest = { + q: string; + page: number; + types?: string[] | string | undefined; +}; \ No newline at end of file