diff --git a/README.md b/README.md index effc20822..3d5e3441f 100644 --- a/README.md +++ b/README.md @@ -564,34 +564,16 @@ client.index('myIndex').getTasks(parameters: TasksQuery): Promise client.index('myIndex').getTask(uid: number): Promise ``` - #### Wait for one task - -##### Using the client - -```ts -client.waitForTask(uid: number, { timeOutMs?: number, intervalMs?: number }): Promise -``` - -##### Using the index - ```ts -client.index('myIndex').waitForTask(uid: number, { timeOutMs?: number, intervalMs?: number }): Promise +client.tasks.waitForTask(uid: number, { timeout?: number, interval?: number }): Promise ``` #### Wait for multiple tasks -##### Using the client - -```ts -client.waitForTasks(uids: number[], { timeOutMs?: number, intervalMs?: number }): Promise -``` - -##### Using the index - ```ts -client.index('myIndex').waitForTasks(uids: number[], { timeOutMs?: number, intervalMs?: number }): Promise +client.tasks.waitForTasks(uids: number[], { timeout?: number, interval?: number }): Promise ``` ### Batches diff --git a/playgrounds/javascript/src/meilisearch.ts b/playgrounds/javascript/src/meilisearch.ts index 0e315f976..0f1818486 100644 --- a/playgrounds/javascript/src/meilisearch.ts +++ b/playgrounds/javascript/src/meilisearch.ts @@ -12,23 +12,22 @@ const index = client.index<{ id: number; title: string; genres: string[] }>( export async function addDocuments(): Promise { await client.deleteIndexIfExists(indexUid); - const task1 = await client.createIndex(indexUid); - await client.waitForTask(task1.taskUid); - - const task2 = await index.addDocuments([ - { id: 1, title: "Carol", genres: ["Romance", "Drama"] }, - { id: 2, title: "Wonder Woman", genres: ["Action", "Adventure"] }, - { id: 3, title: "Life of Pi", genres: ["Adventure", "Drama"] }, - { - id: 4, - title: "Mad Max: Fury Road", - genres: ["Adventure", "Science Fiction"], - }, - { id: 5, title: "Moana", genres: ["Fantasy", "Action"] }, - { id: 6, title: "Philadelphia", genres: ["Drama"] }, - ]); - - await client.index(indexUid).waitForTask(task2.taskUid); + await client.createIndex(indexUid).waitTask(); + + await index + .addDocuments([ + { id: 1, title: "Carol", genres: ["Romance", "Drama"] }, + { id: 2, title: "Wonder Woman", genres: ["Action", "Adventure"] }, + { id: 3, title: "Life of Pi", genres: ["Adventure", "Drama"] }, + { + id: 4, + title: "Mad Max: Fury Road", + genres: ["Adventure", "Science Fiction"], + }, + { id: 5, title: "Moana", genres: ["Fantasy", "Action"] }, + { id: 6, title: "Philadelphia", genres: ["Drama"] }, + ]) + .waitTask(); } export async function getAllHits(element: HTMLDivElement): Promise { diff --git a/src/batch.ts b/src/batch.ts index 32babced7..313b27df2 100644 --- a/src/batch.ts +++ b/src/batch.ts @@ -1,69 +1,38 @@ import type { - Config, - BatchObject, - BatchesQuery, + Batch, BatchesResults, - BatchesResultsObject, -} from "./types.js"; -import { HttpRequests } from "./http-requests.js"; - -class Batch { - uid: BatchObject["uid"]; - details: BatchObject["details"]; - stats: BatchObject["stats"]; - startedAt: BatchObject["startedAt"]; - finishedAt: BatchObject["finishedAt"]; - duration: BatchObject["duration"]; - progress: BatchObject["progress"]; - - constructor(batch: BatchObject) { - this.uid = batch.uid; - this.details = batch.details; - this.stats = batch.stats; - this.startedAt = batch.startedAt; - this.finishedAt = batch.finishedAt; - this.duration = batch.duration; - this.progress = batch.progress; - } -} - -class BatchClient { - httpRequest: HttpRequests; - - constructor(config: Config) { - this.httpRequest = new HttpRequests(config); + TasksOrBatchesQuery, +} from "./types/index.js"; +import type { HttpRequests } from "./http-requests.js"; + +/** + * Class for handling batches. + * + * @see {@link https://www.meilisearch.com/docs/reference/api/batches} + */ +export class BatchClient { + readonly #httpRequest: HttpRequests; + + constructor(httpRequests: HttpRequests) { + this.#httpRequest = httpRequests; } - /** - * Get one batch - * - * @param uid - Unique identifier of the batch - * @returns - */ + /** {@link https://www.meilisearch.com/docs/reference/api/batches#get-one-batch} */ async getBatch(uid: number): Promise { - const batch = await this.httpRequest.get({ + const batch = await this.#httpRequest.get({ path: `batches/${uid}`, }); - return new Batch(batch); + return batch; } - /** - * Get batches - * - * @param parameters - Parameters to browse the batches - * @returns Promise containing all batches - */ - async getBatches(batchesQuery?: BatchesQuery): Promise { - const batches = await this.httpRequest.get({ + /** {@link https://www.meilisearch.com/docs/reference/api/batches#get-batches} */ + async getBatches( + batchesQuery?: TasksOrBatchesQuery, + ): Promise { + const batches = await this.#httpRequest.get({ path: "batches", params: batchesQuery, }); - - return { - ...batches, - results: batches.results.map((batch) => new Batch(batch)), - }; + return batches; } } - -export { BatchClient, Batch }; diff --git a/src/enqueued-task.ts b/src/enqueued-task.ts deleted file mode 100644 index 9665cadbd..000000000 --- a/src/enqueued-task.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { EnqueuedTaskObject } from "./types.js"; - -class EnqueuedTask { - taskUid: EnqueuedTaskObject["taskUid"]; - indexUid: EnqueuedTaskObject["indexUid"]; - status: EnqueuedTaskObject["status"]; - type: EnqueuedTaskObject["type"]; - enqueuedAt: Date; - - constructor(task: EnqueuedTaskObject) { - this.taskUid = task.taskUid; - this.indexUid = task.indexUid; - this.status = task.status; - this.type = task.type; - this.enqueuedAt = new Date(task.enqueuedAt); - } -} - -export { EnqueuedTask }; diff --git a/src/errors/index.ts b/src/errors/index.ts index 615c7b13d..c38869913 100644 --- a/src/errors/index.ts +++ b/src/errors/index.ts @@ -1,4 +1,5 @@ export * from "./meilisearch-api-error.js"; export * from "./meilisearch-request-error.js"; export * from "./meilisearch-error.js"; -export * from "./meilisearch-timeout-error.js"; +export * from "./meilisearch-request-timeout-error.js"; +export * from "./meilisearch-task-timeout-error.js"; diff --git a/src/errors/meilisearch-api-error.ts b/src/errors/meilisearch-api-error.ts index 6d74e764e..aeb1dd0cb 100644 --- a/src/errors/meilisearch-api-error.ts +++ b/src/errors/meilisearch-api-error.ts @@ -1,4 +1,4 @@ -import type { MeiliSearchErrorResponse } from "../types.js"; +import type { MeiliSearchErrorResponse } from "../types/index.js"; import { MeiliSearchError } from "./meilisearch-error.js"; export class MeiliSearchApiError extends MeiliSearchError { diff --git a/src/errors/meilisearch-error.ts b/src/errors/meilisearch-error.ts index 09993bf17..9189cf744 100644 --- a/src/errors/meilisearch-error.ts +++ b/src/errors/meilisearch-error.ts @@ -1,7 +1,3 @@ export class MeiliSearchError extends Error { override name = "MeiliSearchError"; - - constructor(...params: ConstructorParameters) { - super(...params); - } } diff --git a/src/errors/meilisearch-request-timeout-error.ts b/src/errors/meilisearch-request-timeout-error.ts new file mode 100644 index 000000000..ceb010af0 --- /dev/null +++ b/src/errors/meilisearch-request-timeout-error.ts @@ -0,0 +1,13 @@ +import { MeiliSearchError } from "./meilisearch-error.js"; + +/** Error thrown when a HTTP request times out. */ +export class MeiliSearchRequestTimeOutError extends MeiliSearchError { + override name = "MeiliSearchRequestTimeOutError"; + override cause: { timeout: number; requestInit: RequestInit }; + + constructor(timeout: number, requestInit: RequestInit) { + super(`request timed out after ${timeout}ms`); + + this.cause = { timeout, requestInit }; + } +} diff --git a/src/errors/meilisearch-task-timeout-error.ts b/src/errors/meilisearch-task-timeout-error.ts new file mode 100644 index 000000000..da5282c4f --- /dev/null +++ b/src/errors/meilisearch-task-timeout-error.ts @@ -0,0 +1,15 @@ +import { MeiliSearchError } from "./meilisearch-error.js"; + +/** Error thrown when a waiting for a task times out. */ +export class MeiliSearchTaskTimeOutError extends MeiliSearchError { + override name = "MeiliSearchTaskTimeOutError"; + override cause: { taskUid: number; timeout: number }; + + constructor(taskUid: number, timeout: number) { + super( + `timeout of ${timeout}ms has exceeded on task ${taskUid} when waiting for it to be resolved.`, + ); + + this.cause = { taskUid, timeout }; + } +} diff --git a/src/errors/meilisearch-timeout-error.ts b/src/errors/meilisearch-timeout-error.ts deleted file mode 100644 index 2dbbc0286..000000000 --- a/src/errors/meilisearch-timeout-error.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { MeiliSearchError } from "./meilisearch-error.js"; - -export class MeiliSearchTimeOutError extends MeiliSearchError { - override name = "MeiliSearchTimeOutError"; - - constructor(message: string) { - super(message); - } -} diff --git a/src/http-requests.ts b/src/http-requests.ts index 4e3d9ce33..2e3ff400e 100644 --- a/src/http-requests.ts +++ b/src/http-requests.ts @@ -5,12 +5,13 @@ import type { MainRequestOptions, URLSearchParamsRecord, MeiliSearchErrorResponse, -} from "./types.js"; +} from "./types/index.js"; import { PACKAGE_VERSION } from "./package-version.js"; import { MeiliSearchError, MeiliSearchApiError, MeiliSearchRequestError, + MeiliSearchRequestTimeOutError, } from "./errors/index.js"; import { addProtocolIfNotPresent, addTrailingSlash } from "./utils.js"; @@ -79,7 +80,7 @@ const TIMEOUT_ID = {}; * @remarks * This could be a short few straight forward lines using {@link AbortSignal.any} * and {@link AbortSignal.timeout}, but these aren't yet widely supported enough, - * nor polyfillable, at the time of writing. + * nor polyfill -able, at the time of writing. * @returns A new function which starts the timeout, which then returns another * function that clears the timeout */ @@ -240,9 +241,7 @@ export class HttpRequests { throw new MeiliSearchRequestError( url.toString(), Object.is(error, TIMEOUT_ID) - ? new Error(`request timed out after ${this.#requestTimeout}ms`, { - cause: init, - }) + ? new MeiliSearchRequestTimeOutError(this.#requestTimeout!, init) : error, ); } finally { diff --git a/src/index.ts b/src/index.ts index e559e1906..c819e2168 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,8 +1,6 @@ -export * from "./types.js"; +export * from "./types/index.js"; export * from "./errors/index.js"; export * from "./indexes.js"; -export * from "./enqueued-task.js"; -export * from "./task.js"; import { MeiliSearch } from "./meilisearch.js"; /** diff --git a/src/indexes.ts b/src/indexes.ts index 7a044f609..7c4938a4d 100644 --- a/src/indexes.ts +++ b/src/indexes.ts @@ -28,9 +28,6 @@ import type { SearchableAttributes, DisplayedAttributes, TypoTolerance, - WaitOptions, - TasksQuery, - TasksResults, PaginationSettings, Faceting, ResourceResults, @@ -49,22 +46,26 @@ import type { SearchSimilarDocumentsParams, LocalizedAttributes, UpdateDocumentsByFunctionOptions, - EnqueuedTaskObject, ExtraRequestInit, PrefixSearch, RecordAny, -} from "./types.js"; + EnqueuedTaskPromise, +} from "./types/index.js"; import { HttpRequests } from "./http-requests.js"; -import { Task, TaskClient } from "./task.js"; -import { EnqueuedTask } from "./enqueued-task.js"; +import { + getHttpRequestsWithEnqueuedTaskPromise, + TaskClient, + type HttpRequestsWithEnqueuedTaskPromise, +} from "./task.js"; -class Index { +export class Index { uid: string; primaryKey: string | undefined; createdAt: Date | undefined; updatedAt: Date | undefined; httpRequest: HttpRequests; tasks: TaskClient; + readonly #httpRequestsWithTask: HttpRequestsWithEnqueuedTaskPromise; /** * @param config - Request configuration options @@ -75,7 +76,11 @@ class Index { this.uid = uid; this.primaryKey = primaryKey; this.httpRequest = new HttpRequests(config); - this.tasks = new TaskClient(config); + this.tasks = new TaskClient(this.httpRequest, config.defaultWaitOptions); + this.#httpRequestsWithTask = getHttpRequestsWithEnqueuedTaskPromise( + this.httpRequest, + this.tasks, + ); } /// @@ -229,18 +234,19 @@ class Index { * @param config - Request configuration options * @returns Newly created Index object */ - static async create( + static create( uid: string, options: IndexOptions = {}, config: Config, - ): Promise { - const req = new HttpRequests(config); - const task = await req.post({ + ): EnqueuedTaskPromise { + const httpRequests = new HttpRequests(config); + return getHttpRequestsWithEnqueuedTaskPromise( + httpRequests, + new TaskClient(httpRequests), + ).post({ path: "indexes", body: { ...options, uid }, }); - - return new EnqueuedTask(task); } /** @@ -249,13 +255,11 @@ class Index { * @param data - Data to update * @returns Promise to the current Index object with updated information */ - async update(data: IndexOptions): Promise { - const task = await this.httpRequest.patch({ + update(data?: IndexOptions): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.patch({ path: `indexes/${this.uid}`, body: data, }); - - return new EnqueuedTask(task); } /** @@ -263,70 +267,10 @@ class Index { * * @returns Promise which resolves when index is deleted successfully */ - async delete(): Promise { - const task = await this.httpRequest.delete({ + delete(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}`, }); - - return new EnqueuedTask(task); - } - - /// - /// TASKS - /// - - /** - * Get the list of all the tasks of the index. - * - * @param parameters - Parameters to browse the tasks - * @returns Promise containing all tasks - */ - async getTasks(parameters?: TasksQuery): Promise { - return await this.tasks.getTasks({ ...parameters, indexUids: [this.uid] }); - } - - /** - * Get one task of the index. - * - * @param taskUid - Task identifier - * @returns Promise containing a task - */ - async getTask(taskUid: number): Promise { - return await this.tasks.getTask(taskUid); - } - - /** - * Wait for multiple tasks to be processed. - * - * @param taskUids - Tasks identifier - * @param waitOptions - Options on timeout and interval - * @returns Promise containing an array of tasks - */ - async waitForTasks( - taskUids: number[], - { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {}, - ): Promise { - return await this.tasks.waitForTasks(taskUids, { - timeOutMs, - intervalMs, - }); - } - - /** - * Wait for a task to be processed. - * - * @param taskUid - Task identifier - * @param waitOptions - Options on timeout and interval - * @returns Promise containing an array of tasks - */ - async waitForTask( - taskUid: number, - { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {}, - ): Promise { - return await this.tasks.waitForTask(taskUid, { - timeOutMs, - intervalMs, - }); } /// @@ -360,19 +304,17 @@ class Index { ): Promise> { const relativeBaseURL = `indexes/${this.uid}/documents`; - // In case `filter` is provided, use `POST /documents/fetch` - if (params?.filter !== undefined) { - return await this.httpRequest.post>({ - path: `${relativeBaseURL}/fetch`, - body: params, - }); - } else { - // Else use `GET /documents` method - return await this.httpRequest.get>({ - path: relativeBaseURL, - params, - }); - } + return params?.filter !== undefined + ? // In case `filter` is provided, use `POST /documents/fetch` + await this.httpRequest.post>({ + path: `${relativeBaseURL}/fetch`, + body: params, + }) + : // Else use `GET /documents` method + await this.httpRequest.get>({ + path: relativeBaseURL, + params, + }); } /** @@ -386,12 +328,9 @@ class Index { documentId: string | number, parameters?: DocumentQuery, ): Promise { - const fields = (() => { - if (Array.isArray(parameters?.fields)) { - return parameters?.fields?.join(","); - } - return undefined; - })(); + const fields = Array.isArray(parameters?.fields) + ? parameters.fields.join() + : undefined; return await this.httpRequest.get({ path: `indexes/${this.uid}/documents/${documentId}`, @@ -406,17 +345,12 @@ class Index { * @param options - Options on document addition * @returns Promise containing an EnqueuedTask */ - async addDocuments( - documents: T[], - options?: DocumentOptions, - ): Promise { - const task = await this.httpRequest.post({ + addDocuments(documents: T[], options?: DocumentOptions): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.post({ path: `indexes/${this.uid}/documents`, params: options, body: documents, }); - - return new EnqueuedTask(task); } /** @@ -429,19 +363,17 @@ class Index { * @param options - Options on document addition * @returns Promise containing an EnqueuedTask */ - async addDocumentsFromString( + addDocumentsFromString( documents: string, contentType: ContentType, queryParams?: RawDocumentAdditionOptions, - ): Promise { - const task = await this.httpRequest.post({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.post({ path: `indexes/${this.uid}/documents`, body: documents, params: queryParams, contentType, }); - - return new EnqueuedTask(task); } /** @@ -452,17 +384,19 @@ class Index { * @param options - Options on document addition * @returns Promise containing array of enqueued task objects for each batch */ - async addDocumentsInBatches( + addDocumentsInBatches( documents: T[], batchSize = 1000, options?: DocumentOptions, - ): Promise { - const updates = []; + ): EnqueuedTaskPromise[] { + const updates: EnqueuedTaskPromise[] = []; + for (let i = 0; i < documents.length; i += batchSize) { updates.push( - await this.addDocuments(documents.slice(i, i + batchSize), options), + this.addDocuments(documents.slice(i, i + batchSize), options), ); } + return updates; } @@ -473,17 +407,15 @@ class Index { * @param options - Options on document update * @returns Promise containing an EnqueuedTask */ - async updateDocuments( + updateDocuments( documents: Partial[], options?: DocumentOptions, - ): Promise { - const task = await this.httpRequest.put({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/documents`, params: options, body: documents, }); - - return new EnqueuedTask(task); } /** @@ -494,17 +426,19 @@ class Index { * @param options - Options on document update * @returns Promise containing array of enqueued task objects for each batch */ - async updateDocumentsInBatches( + updateDocumentsInBatches( documents: Partial[], batchSize = 1000, options?: DocumentOptions, - ): Promise { - const updates = []; + ): EnqueuedTaskPromise[] { + const updates: EnqueuedTaskPromise[] = []; + for (let i = 0; i < documents.length; i += batchSize) { updates.push( - await this.updateDocuments(documents.slice(i, i + batchSize), options), + this.updateDocuments(documents.slice(i, i + batchSize), options), ); } + return updates; } @@ -518,19 +452,17 @@ class Index { * @param queryParams - Options on raw document addition * @returns Promise containing an EnqueuedTask */ - async updateDocumentsFromString( + updateDocumentsFromString( documents: string, contentType: ContentType, queryParams?: RawDocumentAdditionOptions, - ): Promise { - const task = await this.httpRequest.put({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/documents`, body: documents, params: queryParams, contentType, }); - - return new EnqueuedTask(task); } /** @@ -539,12 +471,10 @@ class Index { * @param documentId - Id of Document to delete * @returns Promise containing an EnqueuedTask */ - async deleteDocument(documentId: string | number): Promise { - const task = await this.httpRequest.delete({ + deleteDocument(documentId: string | number): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/documents/${documentId}`, }); - - return new EnqueuedTask(task); } /** @@ -558,9 +488,9 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async deleteDocuments( + deleteDocuments( params: DocumentsDeletionQuery | DocumentsIds, - ): Promise { + ): EnqueuedTaskPromise { // If params is of type DocumentsDeletionQuery const isDocumentsDeletionQuery = !Array.isArray(params) && typeof params === "object"; @@ -568,12 +498,10 @@ class Index { ? "documents/delete" : "documents/delete-batch"; - const task = await this.httpRequest.post({ + return this.#httpRequestsWithTask.post({ path: `indexes/${this.uid}/${endpoint}`, body: params, }); - - return new EnqueuedTask(task); } /** @@ -581,12 +509,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async deleteAllDocuments(): Promise { - const task = await this.httpRequest.delete({ + deleteAllDocuments(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/documents`, }); - - return new EnqueuedTask(task); } /** @@ -601,15 +527,13 @@ class Index { * @param options - Object containing the function string and related options * @returns Promise containing an EnqueuedTask */ - async updateDocumentsByFunction( + updateDocumentsByFunction( options: UpdateDocumentsByFunctionOptions, - ): Promise { - const task = await this.httpRequest.post({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.post({ path: `indexes/${this.uid}/documents/edit`, body: options, }); - - return new EnqueuedTask(task); } /// @@ -633,13 +557,11 @@ class Index { * @param settings - Object containing parameters with their updated values * @returns Promise containing an EnqueuedTask */ - async updateSettings(settings: Settings): Promise { - const task = await this.httpRequest.patch({ + updateSettings(settings: Settings): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.patch({ path: `indexes/${this.uid}/settings`, body: settings, }); - - return new EnqueuedTask(task); } /** @@ -647,12 +569,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetSettings(): Promise { - const task = await this.httpRequest.delete({ + resetSettings(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings`, }); - - return new EnqueuedTask(task); } /// @@ -676,15 +596,11 @@ class Index { * @param pagination - Pagination object * @returns Promise containing an EnqueuedTask */ - async updatePagination( - pagination: PaginationSettings, - ): Promise { - const task = await this.httpRequest.patch({ + updatePagination(pagination: PaginationSettings): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.patch({ path: `indexes/${this.uid}/settings/pagination`, body: pagination, }); - - return new EnqueuedTask(task); } /** @@ -692,12 +608,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetPagination(): Promise { - const task = await this.httpRequest.delete({ + resetPagination(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/pagination`, }); - - return new EnqueuedTask(task); } /// @@ -721,13 +635,11 @@ class Index { * @param synonyms - Mapping of synonyms with their associated words * @returns Promise containing an EnqueuedTask */ - async updateSynonyms(synonyms: Synonyms): Promise { - const task = await this.httpRequest.put({ + updateSynonyms(synonyms: Synonyms): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/synonyms`, body: synonyms, }); - - return new EnqueuedTask(task); } /** @@ -735,12 +647,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetSynonyms(): Promise { - const task = await this.httpRequest.delete({ + resetSynonyms(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/synonyms`, }); - - return new EnqueuedTask(task); } /// @@ -764,13 +674,11 @@ class Index { * @param stopWords - Array of strings that contains the stop-words. * @returns Promise containing an EnqueuedTask */ - async updateStopWords(stopWords: StopWords): Promise { - const task = await this.httpRequest.put({ + updateStopWords(stopWords: StopWords): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/stop-words`, body: stopWords, }); - - return new EnqueuedTask(task); } /** @@ -778,12 +686,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetStopWords(): Promise { - const task = await this.httpRequest.delete({ + resetStopWords(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/stop-words`, }); - - return new EnqueuedTask(task); } /// @@ -808,13 +714,11 @@ class Index { * importance. * @returns Promise containing an EnqueuedTask */ - async updateRankingRules(rankingRules: RankingRules): Promise { - const task = await this.httpRequest.put({ + updateRankingRules(rankingRules: RankingRules): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/ranking-rules`, body: rankingRules, }); - - return new EnqueuedTask(task); } /** @@ -822,12 +726,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetRankingRules(): Promise { - const task = await this.httpRequest.delete({ + resetRankingRules(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/ranking-rules`, }); - - return new EnqueuedTask(task); } /// @@ -851,15 +753,13 @@ class Index { * @param distinctAttribute - Field name of the distinct-attribute * @returns Promise containing an EnqueuedTask */ - async updateDistinctAttribute( + updateDistinctAttribute( distinctAttribute: DistinctAttribute, - ): Promise { - const task = await this.httpRequest.put({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/distinct-attribute`, body: distinctAttribute, }); - - return new EnqueuedTask(task); } /** @@ -867,12 +767,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetDistinctAttribute(): Promise { - const task = await this.httpRequest.delete({ + resetDistinctAttribute(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/distinct-attribute`, }); - - return new EnqueuedTask(task); } /// @@ -897,15 +795,13 @@ class Index { * that can be used as filters at query time * @returns Promise containing an EnqueuedTask */ - async updateFilterableAttributes( + updateFilterableAttributes( filterableAttributes: FilterableAttributes, - ): Promise { - const task = await this.httpRequest.put({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/filterable-attributes`, body: filterableAttributes, }); - - return new EnqueuedTask(task); } /** @@ -913,12 +809,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetFilterableAttributes(): Promise { - const task = await this.httpRequest.delete({ + resetFilterableAttributes(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/filterable-attributes`, }); - - return new EnqueuedTask(task); } /// @@ -943,15 +837,13 @@ class Index { * can be used to sort search results at query time * @returns Promise containing an EnqueuedTask */ - async updateSortableAttributes( + updateSortableAttributes( sortableAttributes: SortableAttributes, - ): Promise { - const task = await this.httpRequest.put({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/sortable-attributes`, body: sortableAttributes, }); - - return new EnqueuedTask(task); } /** @@ -959,12 +851,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetSortableAttributes(): Promise { - const task = await this.httpRequest.delete({ + resetSortableAttributes(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/sortable-attributes`, }); - - return new EnqueuedTask(task); } /// @@ -989,15 +879,13 @@ class Index { * attributes sorted by order of importance(most to least important) * @returns Promise containing an EnqueuedTask */ - async updateSearchableAttributes( + updateSearchableAttributes( searchableAttributes: SearchableAttributes, - ): Promise { - const task = await this.httpRequest.put({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/searchable-attributes`, body: searchableAttributes, }); - - return new EnqueuedTask(task); } /** @@ -1005,12 +893,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetSearchableAttributes(): Promise { - const task = await this.httpRequest.delete({ + resetSearchableAttributes(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/searchable-attributes`, }); - - return new EnqueuedTask(task); } /// @@ -1035,15 +921,13 @@ class Index { * an index to display * @returns Promise containing an EnqueuedTask */ - async updateDisplayedAttributes( + updateDisplayedAttributes( displayedAttributes: DisplayedAttributes, - ): Promise { - const task = await this.httpRequest.put({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/displayed-attributes`, body: displayedAttributes, }); - - return new EnqueuedTask(task); } /** @@ -1051,12 +935,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetDisplayedAttributes(): Promise { - const task = await this.httpRequest.delete({ + resetDisplayedAttributes(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/displayed-attributes`, }); - - return new EnqueuedTask(task); } /// @@ -1081,15 +963,11 @@ class Index { * settings. * @returns Promise containing object of the enqueued update */ - async updateTypoTolerance( - typoTolerance: TypoTolerance, - ): Promise { - const task = await this.httpRequest.patch({ + updateTypoTolerance(typoTolerance: TypoTolerance): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.patch({ path: `indexes/${this.uid}/settings/typo-tolerance`, body: typoTolerance, }); - - return new EnqueuedTask(task); } /** @@ -1097,12 +975,10 @@ class Index { * * @returns Promise containing object of the enqueued update */ - async resetTypoTolerance(): Promise { - const task = await this.httpRequest.delete({ + resetTypoTolerance(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/typo-tolerance`, }); - - return new EnqueuedTask(task); } /// @@ -1126,13 +1002,11 @@ class Index { * @param faceting - Faceting index settings object * @returns Promise containing an EnqueuedTask */ - async updateFaceting(faceting: Faceting): Promise { - const task = await this.httpRequest.patch({ + updateFaceting(faceting: Faceting): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.patch({ path: `indexes/${this.uid}/settings/faceting`, body: faceting, }); - - return new EnqueuedTask(task); } /** @@ -1140,12 +1014,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetFaceting(): Promise { - const task = await this.httpRequest.delete({ + resetFaceting(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/faceting`, }); - - return new EnqueuedTask(task); } /// @@ -1169,15 +1041,11 @@ class Index { * @param separatorTokens - Array that contains separator tokens. * @returns Promise containing an EnqueuedTask or null */ - async updateSeparatorTokens( - separatorTokens: SeparatorTokens, - ): Promise { - const task = await this.httpRequest.put({ + updateSeparatorTokens(separatorTokens: SeparatorTokens): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/separator-tokens`, body: separatorTokens, }); - - return new EnqueuedTask(task); } /** @@ -1185,12 +1053,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetSeparatorTokens(): Promise { - const task = await this.httpRequest.delete({ + resetSeparatorTokens(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/separator-tokens`, }); - - return new EnqueuedTask(task); } /// @@ -1214,15 +1080,13 @@ class Index { * @param nonSeparatorTokens - Array that contains non-separator tokens. * @returns Promise containing an EnqueuedTask or null */ - async updateNonSeparatorTokens( + updateNonSeparatorTokens( nonSeparatorTokens: NonSeparatorTokens, - ): Promise { - const task = await this.httpRequest.put({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/non-separator-tokens`, body: nonSeparatorTokens, }); - - return new EnqueuedTask(task); } /** @@ -1230,12 +1094,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetNonSeparatorTokens(): Promise { - const task = await this.httpRequest.delete({ + resetNonSeparatorTokens(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/non-separator-tokens`, }); - - return new EnqueuedTask(task); } /// @@ -1259,13 +1121,11 @@ class Index { * @param dictionary - Array that contains the new dictionary settings. * @returns Promise containing an EnqueuedTask or null */ - async updateDictionary(dictionary: Dictionary): Promise { - const task = await this.httpRequest.put({ + updateDictionary(dictionary: Dictionary): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/dictionary`, body: dictionary, }); - - return new EnqueuedTask(task); } /** @@ -1273,12 +1133,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetDictionary(): Promise { - const task = await this.httpRequest.delete({ + resetDictionary(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/dictionary`, }); - - return new EnqueuedTask(task); } /// @@ -1303,15 +1161,13 @@ class Index { * precision settings. * @returns Promise containing an EnqueuedTask or null */ - async updateProximityPrecision( + updateProximityPrecision( proximityPrecision: ProximityPrecision, - ): Promise { - const task = await this.httpRequest.put({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/proximity-precision`, body: proximityPrecision, }); - - return new EnqueuedTask(task); } /** @@ -1319,12 +1175,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetProximityPrecision(): Promise { - const task = await this.httpRequest.delete({ + resetProximityPrecision(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/proximity-precision`, }); - - return new EnqueuedTask(task); } /// @@ -1348,13 +1202,11 @@ class Index { * @param embedders - Object that contains the new embedders settings. * @returns Promise containing an EnqueuedTask or null */ - async updateEmbedders(embedders: Embedders): Promise { - const task = await this.httpRequest.patch({ + updateEmbedders(embedders: Embedders): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.patch({ path: `indexes/${this.uid}/settings/embedders`, body: embedders, }); - - return new EnqueuedTask(task); } /** @@ -1362,12 +1214,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetEmbedders(): Promise { - const task = await this.httpRequest.delete({ + resetEmbedders(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/embedders`, }); - - return new EnqueuedTask(task); } /// @@ -1391,15 +1241,11 @@ class Index { * @param searchCutoffMs - Object containing SearchCutoffMsSettings * @returns Promise containing an EnqueuedTask */ - async updateSearchCutoffMs( - searchCutoffMs: SearchCutoffMs, - ): Promise { - const task = await this.httpRequest.put({ + updateSearchCutoffMs(searchCutoffMs: SearchCutoffMs): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/search-cutoff-ms`, body: searchCutoffMs, }); - - return new EnqueuedTask(task); } /** @@ -1407,12 +1253,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetSearchCutoffMs(): Promise { - const task = await this.httpRequest.delete({ + resetSearchCutoffMs(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/search-cutoff-ms`, }); - - return new EnqueuedTask(task); } /// @@ -1436,15 +1280,13 @@ class Index { * @param localizedAttributes - Localized attributes object * @returns Promise containing an EnqueuedTask */ - async updateLocalizedAttributes( + updateLocalizedAttributes( localizedAttributes: LocalizedAttributes, - ): Promise { - const task = await this.httpRequest.put({ + ): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/localized-attributes`, body: localizedAttributes, }); - - return new EnqueuedTask(task); } /** @@ -1452,12 +1294,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetLocalizedAttributes(): Promise { - const task = await this.httpRequest.delete({ + resetLocalizedAttributes(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/localized-attributes`, }); - - return new EnqueuedTask(task); } /// @@ -1481,12 +1321,11 @@ class Index { * @param facetSearch - Boolean value * @returns Promise containing an EnqueuedTask */ - async updateFacetSearch(facetSearch: boolean): Promise { - const task = await this.httpRequest.put({ + updateFacetSearch(facetSearch: boolean): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/facet-search`, body: facetSearch, }); - return new EnqueuedTask(task); } /** @@ -1494,11 +1333,10 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetFacetSearch(): Promise { - const task = await this.httpRequest.delete({ + resetFacetSearch(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/facet-search`, }); - return new EnqueuedTask(task); } /// @@ -1522,12 +1360,11 @@ class Index { * @param prefixSearch - PrefixSearch value * @returns Promise containing an EnqueuedTask */ - async updatePrefixSearch(prefixSearch: PrefixSearch): Promise { - const task = await this.httpRequest.put({ + updatePrefixSearch(prefixSearch: PrefixSearch): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.put({ path: `indexes/${this.uid}/settings/prefix-search`, body: prefixSearch, }); - return new EnqueuedTask(task); } /** @@ -1535,12 +1372,9 @@ class Index { * * @returns Promise containing an EnqueuedTask */ - async resetPrefixSearch(): Promise { - const task = await this.httpRequest.delete({ + resetPrefixSearch(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.uid}/settings/prefix-search`, }); - return new EnqueuedTask(task); } } - -export { Index }; diff --git a/src/meilisearch.ts b/src/meilisearch.ts index f5c6a5784..25f1c4e8d 100644 --- a/src/meilisearch.ts +++ b/src/meilisearch.ts @@ -20,29 +20,40 @@ import type { IndexesResults, KeysQuery, KeysResults, - EnqueuedTaskObject, - SwapIndexesParams, + IndexSwap, MultiSearchParams, FederatedMultiSearchParams, - ExtraRequestInit, - BatchesResults, - BatchesQuery, MultiSearchResponseOrSearchResponse, + EnqueuedTaskPromise, + ExtraRequestInit, Network, RecordAny, -} from "./types.js"; -import { ErrorStatusCode } from "./types.js"; +} from "./types/index.js"; +import { ErrorStatusCode } from "./types/index.js"; import { HttpRequests } from "./http-requests.js"; -import { TaskClient } from "./task.js"; -import { EnqueuedTask } from "./enqueued-task.js"; -import { type Batch, BatchClient } from "./batch.js"; -import type { MeiliSearchApiError } from "./errors/meilisearch-api-error.js"; +import { + getHttpRequestsWithEnqueuedTaskPromise, + TaskClient, + type HttpRequestsWithEnqueuedTaskPromise, +} from "./task.js"; +import { BatchClient } from "./batch.js"; +import type { MeiliSearchApiError } from "./errors/index.js"; export class MeiliSearch { config: Config; httpRequest: HttpRequests; - tasks: TaskClient; - batches: BatchClient; + + readonly #taskClient: TaskClient; + get tasks() { + return this.#taskClient; + } + + readonly #batchClient: BatchClient; + get batches() { + return this.#batchClient; + } + + readonly #httpRequestsWithTask: HttpRequestsWithEnqueuedTaskPromise; /** * Creates new MeiliSearch instance @@ -52,8 +63,17 @@ export class MeiliSearch { constructor(config: Config) { this.config = config; this.httpRequest = new HttpRequests(config); - this.tasks = new TaskClient(config); - this.batches = new BatchClient(config); + + this.#taskClient = new TaskClient( + this.httpRequest, + config.defaultWaitOptions, + ); + this.#batchClient = new BatchClient(this.httpRequest); + + this.#httpRequestsWithTask = getHttpRequestsWithEnqueuedTaskPromise( + this.httpRequest, + this.tasks, + ); } /** @@ -128,11 +148,8 @@ export class MeiliSearch { * @param options - Index options * @returns Promise returning Index instance */ - async createIndex( - uid: string, - options?: IndexOptions, - ): Promise { - return await Index.create(uid, options, this.config); + createIndex(uid: string, options?: IndexOptions): EnqueuedTaskPromise { + return Index.create(uid, options, this.config); } /** @@ -142,11 +159,8 @@ export class MeiliSearch { * @param options - Index options to update * @returns Promise returning Index instance after updating */ - async updateIndex( - uid: string, - options: IndexOptions = {}, - ): Promise { - return await new Index(this.config, uid).update(options); + updateIndex(uid: string, options?: IndexOptions): EnqueuedTaskPromise { + return new Index(this.config, uid).update(options); } /** @@ -155,8 +169,8 @@ export class MeiliSearch { * @param uid - The index UID * @returns Promise which resolves when index is deleted successfully */ - async deleteIndex(uid: string): Promise { - return await new Index(this.config, uid).delete(); + deleteIndex(uid: string): EnqueuedTaskPromise { + return new Index(this.config, uid).delete(); } /** @@ -188,14 +202,11 @@ export class MeiliSearch { * @param params - List of indexes tuples to swap. * @returns Promise returning object of the enqueued task */ - async swapIndexes(params: SwapIndexesParams): Promise { - const url = "/swap-indexes"; - const taks = await this.httpRequest.post({ - path: url, + swapIndexes(params: IndexSwap[]): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.post({ + path: "/swap-indexes", body: params, }); - - return new EnqueuedTask(taks); } /// @@ -287,104 +298,6 @@ export class MeiliSearch { }); } - /// - /// TASKS - /// - - /** - * Get the list of all client tasks - * - * @param parameters - Parameters to browse the tasks - * @returns Promise returning all tasks - */ - async getTasks( - ...params: Parameters - ): ReturnType { - return await this.tasks.getTasks(...params); - } - - /** - * Get one task on the client scope - * - * @param taskUid - Task identifier - * @returns Promise returning a task - */ - async getTask( - ...params: Parameters - ): ReturnType { - return await this.tasks.getTask(...params); - } - - /** - * Wait for multiple tasks to be finished. - * - * @param taskUids - Tasks identifier - * @param waitOptions - Options on timeout and interval - * @returns Promise returning an array of tasks - */ - async waitForTasks( - ...params: Parameters - ): ReturnType { - return await this.tasks.waitForTasks(...params); - } - - /** - * Wait for a task to be finished. - * - * @param taskUid - Task identifier - * @param waitOptions - Options on timeout and interval - * @returns Promise returning an array of tasks - */ - async waitForTask( - ...params: Parameters - ): ReturnType { - return await this.tasks.waitForTask(...params); - } - - /** - * Cancel a list of enqueued or processing tasks. - * - * @param parameters - Parameters to filter the tasks. - * @returns Promise containing an EnqueuedTask - */ - async cancelTasks( - ...params: Parameters - ): ReturnType { - return await this.tasks.cancelTasks(...params); - } - - /** - * Delete a list of tasks. - * - * @param parameters - Parameters to filter the tasks. - * @returns Promise containing an EnqueuedTask - */ - async deleteTasks( - ...params: Parameters - ): ReturnType { - return await this.tasks.deleteTasks(...params); - } - - /** - * Get all the batches - * - * @param parameters - Parameters to browse the batches - * @returns Promise returning all batches - */ - async getBatches(parameters: BatchesQuery = {}): Promise { - return await this.batches.getBatches(parameters); - } - - /** - * Get one batch - * - * @param uid - Batch identifier - * @returns Promise returning a batch - */ - async getBatch(uid: number): Promise { - return await this.batches.getBatch(uid); - } - /// /// KEYS /// @@ -521,12 +434,10 @@ export class MeiliSearch { * * @returns Promise returning object of the enqueued task */ - async createDump(): Promise { - const task = await this.httpRequest.post({ + createDump(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.post({ path: "dumps", }); - - return new EnqueuedTask(task); } /// @@ -538,11 +449,9 @@ export class MeiliSearch { * * @returns Promise returning object of the enqueued task */ - async createSnapshot(): Promise { - const task = await this.httpRequest.post({ + createSnapshot(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.post({ path: "snapshots", }); - - return new EnqueuedTask(task); } } diff --git a/src/task.ts b/src/task.ts index 912e1795a..52637e18b 100644 --- a/src/task.ts +++ b/src/task.ts @@ -1,169 +1,210 @@ -import { MeiliSearchTimeOutError } from "./errors/index.js"; +import { MeiliSearchTaskTimeOutError } from "./errors/index.js"; import type { - Config, WaitOptions, - TasksQuery, + TasksOrBatchesQuery, TasksResults, - TaskObject, - CancelTasksQuery, - TasksResultsObject, - DeleteTasksQuery, - EnqueuedTaskObject, -} from "./types.js"; -import { TaskStatus } from "./types.js"; -import { HttpRequests } from "./http-requests.js"; -import { sleep } from "./utils.js"; -import { EnqueuedTask } from "./enqueued-task.js"; - -class Task { - indexUid: TaskObject["indexUid"]; - status: TaskObject["status"]; - type: TaskObject["type"]; - uid: TaskObject["uid"]; - batchUid: TaskObject["batchUid"]; - canceledBy: TaskObject["canceledBy"]; - details: TaskObject["details"]; - error: TaskObject["error"]; - duration: TaskObject["duration"]; - startedAt: Date; - enqueuedAt: Date; - finishedAt: Date; - - constructor(task: TaskObject) { - this.indexUid = task.indexUid; - this.status = task.status; - this.type = task.type; - this.uid = task.uid; - this.batchUid = task.batchUid; - this.details = task.details; - this.canceledBy = task.canceledBy; - this.error = task.error; - this.duration = task.duration; - - this.startedAt = new Date(task.startedAt); - this.enqueuedAt = new Date(task.enqueuedAt); - this.finishedAt = new Date(task.finishedAt); - } + Task, + DeleteOrCancelTasksQuery, + EnqueuedTask, + EnqueuedTaskPromise, + TaskUidOrEnqueuedTask, + ExtraRequestInit, +} from "./types/index.js"; +import type { HttpRequests } from "./http-requests.js"; + +// TODO: Convert to Symbol("timeout id") when Node.js 18 is dropped +/** + * Used to identify whether an error is a timeout error in + * {@link TaskClient.waitForTask}. + */ +const TIMEOUT_ID = {}; + +/** + * @returns A function which defines an extra function property on a + * {@link Promise}, which resolves to {@link EnqueuedTask}, which awaits it and + * resolves to a {@link Task}. + */ +function getWaitTaskApplier( + taskClient: TaskClient, +): (enqueuedTaskPromise: Promise) => EnqueuedTaskPromise { + return function ( + enqueuedTaskPromise: Promise, + ): EnqueuedTaskPromise { + return Object.defineProperty( + enqueuedTaskPromise, + "waitTask" satisfies keyof Pick, + { + async value(waitOptions?: WaitOptions): Promise { + return await taskClient.waitForTask( + await enqueuedTaskPromise, + waitOptions, + ); + }, + }, + ) as EnqueuedTaskPromise; + }; } -class TaskClient { - httpRequest: HttpRequests; +const getTaskUid = (taskUidOrEnqueuedTask: TaskUidOrEnqueuedTask): number => + typeof taskUidOrEnqueuedTask === "number" + ? taskUidOrEnqueuedTask + : taskUidOrEnqueuedTask.taskUid; - constructor(config: Config) { - this.httpRequest = new HttpRequests(config); +/** + * Class for handling tasks. + * + * @see {@link https://www.meilisearch.com/docs/reference/api/tasks} + */ +export class TaskClient { + readonly #httpRequest: HttpRequests; + readonly #defaultTimeout: number; + readonly #defaultInterval: number; + readonly #applyWaitTask: ReturnType; + + constructor(httpRequest: HttpRequests, defaultWaitOptions?: WaitOptions) { + this.#httpRequest = httpRequest; + this.#defaultTimeout = defaultWaitOptions?.timeout ?? 5_000; + this.#defaultInterval = defaultWaitOptions?.interval ?? 50; + this.#applyWaitTask = getWaitTaskApplier(this); } - /** - * Get one task - * - * @param uid - Unique identifier of the task - * @returns - */ - async getTask(uid: number): Promise { - const taskItem = await this.httpRequest.get({ + /** {@link https://www.meilisearch.com/docs/reference/api/tasks#get-one-task} */ + async getTask( + uid: number, + // TODO: Need to do this for all other methods: https://github.com/meilisearch/meilisearch-js/issues/1476 + extraRequestInit?: ExtraRequestInit, + ): Promise { + const task = await this.#httpRequest.get({ path: `tasks/${uid}`, + extraRequestInit, }); - return new Task(taskItem); + return task; } - /** - * Get tasks - * - * @param params - Parameters to browse the tasks - * @returns Promise containing all tasks - */ - async getTasks(params?: TasksQuery): Promise { - const tasks = await this.httpRequest.get({ + /** {@link https://www.meilisearch.com/docs/reference/api/tasks#get-tasks} */ + async getTasks(params?: TasksOrBatchesQuery): Promise { + const tasks = await this.#httpRequest.get({ path: "tasks", params, }); - - return { - ...tasks, - results: tasks.results.map((task) => new Task(task)), - }; + return tasks; } /** - * Wait for a task to be processed. + * Wait for an enqueued task to be processed. * - * @param taskUid - Task identifier - * @param options - Additional configuration options - * @returns Promise returning a task after it has been processed + * @remarks + * If an {@link EnqueuedTask} needs to be awaited instantly, it is recommended + * to instead use {@link EnqueuedTaskPromise.waitTask}, which is available on + * any method that returns an {@link EnqueuedTaskPromise}. */ async waitForTask( - taskUid: number, - { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {}, + taskUidOrEnqueuedTask: TaskUidOrEnqueuedTask, + options?: WaitOptions, ): Promise { - const startingTime = Date.now(); - while (Date.now() - startingTime < timeOutMs) { - const response = await this.getTask(taskUid); - if ( - !( - [ - TaskStatus.TASK_ENQUEUED, - TaskStatus.TASK_PROCESSING, - ] as readonly string[] - ).includes(response.status) - ) - return response; - await sleep(intervalMs); + const taskUid = getTaskUid(taskUidOrEnqueuedTask); + const timeout = options?.timeout ?? this.#defaultTimeout; + const interval = options?.interval ?? this.#defaultInterval; + + const ac = timeout > 0 ? new AbortController() : null; + + const toId = + ac !== null + ? setTimeout(() => void ac.abort(TIMEOUT_ID), timeout) + : undefined; + + try { + for (;;) { + const task = await this.getTask(taskUid, { signal: ac?.signal }); + + if (task.status !== "enqueued" && task.status !== "processing") { + clearTimeout(toId); + return task; + } + + if (interval > 0) { + await new Promise((resolve) => setTimeout(resolve, interval)); + } + } + } catch (error) { + throw Object.is((error as Error).cause, TIMEOUT_ID) + ? new MeiliSearchTaskTimeOutError(taskUid, timeout) + : error; } - throw new MeiliSearchTimeOutError( - `timeout of ${timeOutMs}ms has exceeded on process ${taskUid} when waiting a task to be resolved.`, - ); } /** - * Waits for multiple tasks to be processed + * Lazily wait for multiple enqueued tasks to be processed. * - * @param taskUids - Tasks identifier list - * @param options - Wait options - * @returns Promise returning a list of tasks after they have been processed + * @remarks + * In this case {@link WaitOptions.timeout} is the maximum time to wait for any + * one task, not for all of the tasks to complete. */ + async *waitForTasksIter( + taskUidsOrEnqueuedTasks: + | Iterable + | AsyncIterable, + options?: WaitOptions, + ): AsyncGenerator { + for await (const taskUidOrEnqueuedTask of taskUidsOrEnqueuedTasks) { + yield await this.waitForTask(taskUidOrEnqueuedTask, options); + } + } + + /** Wait for multiple enqueued tasks to be processed. */ async waitForTasks( - taskUids: number[], - { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {}, + ...params: Parameters ): Promise { const tasks: Task[] = []; - for (const taskUid of taskUids) { - const task = await this.waitForTask(taskUid, { - timeOutMs, - intervalMs, - }); + + for await (const task of this.waitForTasksIter(...params)) { tasks.push(task); } + return tasks; } - /** - * Cancel a list of enqueued or processing tasks. - * - * @param params - Parameters to filter the tasks. - * @returns Promise containing an EnqueuedTask - */ - async cancelTasks(params?: CancelTasksQuery): Promise { - const task = await this.httpRequest.post({ - path: "tasks/cancel", - params, - }); - - return new EnqueuedTask(task); + /** {@link https://www.meilisearch.com/docs/reference/api/tasks#cancel-tasks} */ + cancelTasks(params: DeleteOrCancelTasksQuery): EnqueuedTaskPromise { + return this.#applyWaitTask( + this.#httpRequest.post({ + path: "tasks/cancel", + params, + }), + ); } - /** - * Delete a list tasks. - * - * @param params - Parameters to filter the tasks. - * @returns Promise containing an EnqueuedTask - */ - async deleteTasks(params?: DeleteTasksQuery): Promise { - const task = await this.httpRequest.delete({ - path: "tasks", - params, - }); - return new EnqueuedTask(task); + /** {@link https://www.meilisearch.com/docs/reference/api/tasks#delete-tasks} */ + deleteTasks(params: DeleteOrCancelTasksQuery): EnqueuedTaskPromise { + return this.#applyWaitTask( + this.#httpRequest.delete({ + path: "tasks", + params, + }), + ); } } -export { TaskClient, Task }; +type PickedHttpRequestMethods = Pick< + HttpRequests, + "post" | "put" | "patch" | "delete" +>; +export type HttpRequestsWithEnqueuedTaskPromise = { + [TKey in keyof PickedHttpRequestMethods]: ( + ...params: Parameters + ) => EnqueuedTaskPromise; +}; + +export function getHttpRequestsWithEnqueuedTaskPromise( + httpRequest: HttpRequests, + taskClient: TaskClient, +): HttpRequestsWithEnqueuedTaskPromise { + const applyWaitTask = getWaitTaskApplier(taskClient); + + return { + post: (...params) => applyWaitTask(httpRequest.post(...params)), + put: (...params) => applyWaitTask(httpRequest.put(...params)), + patch: (...params) => applyWaitTask(httpRequest.patch(...params)), + delete: (...params) => applyWaitTask(httpRequest.delete(...params)), + }; +} diff --git a/src/token.ts b/src/token.ts index e511df250..54640fb0d 100644 --- a/src/token.ts +++ b/src/token.ts @@ -3,7 +3,7 @@ import type { TenantTokenGeneratorOptions, TenantTokenHeader, TokenClaims, -} from "./types.js"; +} from "./types/index.js"; function getOptionsWithDefaults(options: TenantTokenGeneratorOptions) { const { @@ -15,6 +15,7 @@ function getOptionsWithDefaults(options: TenantTokenGeneratorOptions) { return { searchRules, algorithm, force, ...restOfOptions }; } +// TODO: There's no point in this, or maybe even the above fn type TenantTokenGeneratorOptionsWithDefaults = ReturnType< typeof getOptionsWithDefaults >; diff --git a/src/types/index.ts b/src/types/index.ts new file mode 100644 index 000000000..2a13bc669 --- /dev/null +++ b/src/types/index.ts @@ -0,0 +1,3 @@ +export * from "./task_and_batch.js"; +export * from "./token.js"; +export * from "./types.js"; diff --git a/src/types/shared.ts b/src/types/shared.ts new file mode 100644 index 000000000..d475d6948 --- /dev/null +++ b/src/types/shared.ts @@ -0,0 +1,18 @@ +import type { RecordAny } from "./types.js"; + +export type CursorResults = { + results: T[]; + limit: number; + from: number; + next: number; + total: number; +}; + +export type NonNullableDeepRecordValues = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [P in keyof T]: T[P] extends any[] + ? Array> + : T[P] extends RecordAny + ? NonNullableDeepRecordValues + : NonNullable; +}; diff --git a/src/types/task_and_batch.ts b/src/types/task_and_batch.ts new file mode 100644 index 000000000..9c8c5d4d6 --- /dev/null +++ b/src/types/task_and_batch.ts @@ -0,0 +1,193 @@ +import type { Settings } from "./types.js"; +import type { CursorResults } from "./shared.js"; +import type { MeiliSearchErrorResponse } from "./types.js"; + +/** Options for awaiting {@link EnqueuedTask}. */ +export type WaitOptions = { + /** + * Milliseconds until timeout error will be thrown for each awaited task. A + * value of less than `1` disables it. + * + * @defaultValue `5000` + */ + timeout?: number; + /** + * Task polling interval in milliseconds. A value of less than `1` disables + * it. + * + * @defaultValue `50` + */ + interval?: number; +}; + +/** {@link https://www.meilisearch.com/docs/reference/api/tasks#status} */ +export type TaskStatus = + | "enqueued" + | "processing" + | "succeeded" + | "failed" + | "canceled"; + +/** {@link https://www.meilisearch.com/docs/reference/api/tasks#type} */ +export type TaskType = + | "documentAdditionOrUpdate" + | "documentEdition" + | "documentDeletion" + | "settingsUpdate" + | "indexCreation" + | "indexDeletion" + | "indexUpdate" + | "indexSwap" + | "taskCancelation" + | "taskDeletion" + | "dumpCreation" + | "snapshotCreation"; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/tasks#query-parameters} + * + * @see `meilisearch::routes::tasks::TasksFilterQuery` at {@link https://github.com/meilisearch/meilisearch} + */ +export type TasksOrBatchesQuery = { + limit?: number; + from?: number; + reverse?: boolean; + batchUids?: number[]; + uids?: number[]; + canceledBy?: number[]; + types?: TaskType[]; + statuses?: TaskStatus[]; + indexUids?: string[]; + afterEnqueuedAt?: string; + beforeEnqueuedAt?: string; + afterStartedAt?: string; + beforeStartedAt?: string; + afterFinishedAt?: string; + beforeFinishedAt?: string; +}; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/tasks#query-parameters-1} + * {@link https://www.meilisearch.com/docs/reference/api/tasks#query-parameters-2} + * + * @see `meilisearch::routes::tasks::TaskDeletionOrCancelationQuery` at {@link https://github.com/meilisearch/meilisearch} + */ +export type DeleteOrCancelTasksQuery = Omit< + TasksOrBatchesQuery, + "limit" | "from" | "reverse" +>; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/tasks#summarized-task-object} + * + * @see `meilisearch::routes::SummarizedTaskView` at {@link https://github.com/meilisearch/meilisearch} + */ +export type EnqueuedTask = { + taskUid: number; + indexUid: string | null; + status: TaskStatus; + type: TaskType; + enqueuedAt: string; +}; + +/** Either a number or an {@link EnqueuedTask}. */ +export type TaskUidOrEnqueuedTask = EnqueuedTask["taskUid"] | EnqueuedTask; + +/** {@link https://www.meilisearch.com/docs/reference/api/tasks#indexswap} */ +export type IndexSwap = { indexes: [string, string] }; + +/** {@link https://www.meilisearch.com/docs/reference/api/tasks#details} */ +export type TaskDetails = Settings & { + receivedDocuments?: number; + indexedDocuments?: number; + editedDocuments?: number; + primaryKey?: string; + providedIds?: number; + deletedDocuments?: number; + matchedTasks?: number; + canceledTasks?: number; + deletedTasks?: number; + originalFilter?: string | null; + dumpUid?: string | null; + context?: Record | null; + function?: string; + swaps?: IndexSwap[]; +}; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/tasks#task-object} + * + * @see `meilisearch_types::task_view::TaskView` at {@link https://github.com/meilisearch/meilisearch} + */ +export type Task = Omit & { + uid: number; + batchUid: number | null; + canceledBy: number | null; + details?: TaskDetails; + error: MeiliSearchErrorResponse | null; + duration: string | null; + startedAt: string | null; + finishedAt: string | null; +}; + +/** + * A {@link Promise} resolving to an {@link EnqueuedTask} with an extra function + * that returns a Promise that resolves to a {@link Task}. + */ +export type EnqueuedTaskPromise = Promise & { + /** + * Function that, through polling, awaits the {@link EnqueuedTask} resolved by + * {@link EnqueuedTaskPromise}. + */ + waitTask: (waitOptions?: WaitOptions) => Promise; +}; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/tasks#response} + * + * @see `meilisearch::routes::tasks::AllTasks` at {@link https://github.com/meilisearch/meilisearch} + */ +export type TasksResults = CursorResults; + +/** {@link https://www.meilisearch.com/docs/reference/api/batches#steps} */ +type BatchProgressStep = { + currentStep: string; + finished: number; + total: number; +}; + +/** {@link https://www.meilisearch.com/docs/reference/api/batches#progress} */ +type BatchProgress = { + steps: BatchProgressStep[]; + percentage: number; +}; + +/** {@link https://www.meilisearch.com/docs/reference/api/batches#stats} */ +type BatchStats = { + totalNbTasks: number; + status: Record; + types: Record; + indexUids: Record; +}; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/batches#batch-object} + * + * @see `meilisearch_types::batch_view::BatchView` at {@link https://github.com/meilisearch/meilisearch} + */ +export type Batch = { + uid: number; + progress: BatchProgress | null; + details: TaskDetails; + stats: BatchStats; + duration: string | null; + startedAt: string; + finishedAt: string | null; +}; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/batches#response} + * + * @see `meilisearch::routes::batches::AllBatches` at {@link https://github.com/meilisearch/meilisearch} + */ +export type BatchesResults = CursorResults; diff --git a/src/types/token.ts b/src/types/token.ts new file mode 100644 index 000000000..3ca1d570e --- /dev/null +++ b/src/types/token.ts @@ -0,0 +1,73 @@ +import type { Filter } from "./types.js"; + +/** @see {@link TokenSearchRules} */ +export type TokenIndexRules = { filter?: Filter }; + +/** + * {@link https://www.meilisearch.com/docs/learn/security/tenant_token_reference#search-rules} + * + * @remarks + * Not well documented. + * @see {@link https://github.com/meilisearch/meilisearch/blob/b21d7aedf9096539041362d438e973a18170f3fc/crates/meilisearch-auth/src/lib.rs#L271-L277 | GitHub source code} + */ +export type TokenSearchRules = + | Record + | string[]; + +/** Options object for tenant token generation. */ +export type TenantTokenGeneratorOptions = { + /** API key used to sign the token. */ + apiKey: string; + /** + * The uid of the api key used as issuer of the token. + * + * @see {@link https://www.meilisearch.com/docs/learn/security/tenant_token_reference#api-key-uid} + */ + apiKeyUid: string; + /** + * Search rules that are applied to every search. + * + * @defaultValue `["*"]` + */ + searchRules?: TokenSearchRules; + /** + * {@link https://en.wikipedia.org/wiki/Unix_time | UNIX timestamp} or + * {@link Date} object at which the token expires. + * + * @see {@link https://www.meilisearch.com/docs/learn/security/tenant_token_reference#expiry-date} + */ + expiresAt?: number | Date; + /** + * Encryption algorithm used to sign the JWT. Supported values by Meilisearch + * are HS256, HS384, HS512. (HS[number] means HMAC using SHA-[number]) + * + * @defaultValue `"HS256"` + * @see {@link https://www.meilisearch.com/docs/learn/security/generate_tenant_token_scratch#prepare-token-header} + */ + algorithm?: `HS${256 | 384 | 512}`; + /** + * By default if a non-safe environment is detected, an error is thrown. + * Setting this to `true` skips environment detection. This is intended for + * server-side environments where detection fails or usage in a browser is + * intentional (Use at your own risk). + * + * @defaultValue `false` + */ + force?: boolean; +}; + +/** + * @see {@link https://www.meilisearch.com/docs/learn/security/tenant_token_reference | Tenant token payload reference} + * @see {@link https://github.com/meilisearch/meilisearch/blob/b21d7aedf9096539041362d438e973a18170f3fc/crates/meilisearch/src/extractors/authentication/mod.rs#L334-L340 | GitHub source code} + */ +export type TokenClaims = { + searchRules: TokenSearchRules; + exp?: number; + apiKeyUid: string; +}; + +/** JSON Web Token header. */ +export type TenantTokenHeader = { + alg: NonNullable; + typ: "JWT"; +}; diff --git a/src/types.ts b/src/types/types.ts similarity index 79% rename from src/types.ts rename to src/types/types.ts index af3350f5e..9b1640f14 100644 --- a/src/types.ts +++ b/src/types/types.ts @@ -2,10 +2,9 @@ // Project: https://github.com/meilisearch/meilisearch-js // Definitions by: qdequele // Definitions: https://github.com/meilisearch/meilisearch-js -// TypeScript Version: ^3.8.3 +// TypeScript Version: ^5.8.2 -import { Task } from "./task.js"; -import { Batch } from "./batch.js"; +import type { WaitOptions } from "./task_and_batch.js"; // eslint-disable-next-line @typescript-eslint/no-explicit-any export type RecordAny = Record; @@ -77,6 +76,7 @@ export type Config = { httpClient?: (...args: Parameters) => Promise; /** Timeout in milliseconds for each HTTP request. */ timeout?: number; + defaultWaitOptions?: WaitOptions; }; /** Main options of a request. */ @@ -141,8 +141,8 @@ export type IndexOptions = { export type IndexObject = { uid: string; primaryKey?: string; - createdAt: Date; - updatedAt: Date; + createdAt: string; + updatedAt: string; }; export type IndexesQuery = ResourceQuery & {}; @@ -642,245 +642,6 @@ export type Settings = { prefixSearch?: "indexingTime" | "disabled"; }; -/* - ** TASKS - */ - -export const TaskStatus = { - TASK_SUCCEEDED: "succeeded", - TASK_PROCESSING: "processing", - TASK_FAILED: "failed", - TASK_ENQUEUED: "enqueued", - TASK_CANCELED: "canceled", -} as const; - -export type TaskStatus = (typeof TaskStatus)[keyof typeof TaskStatus]; - -export const TaskTypes = { - DOCUMENTS_ADDITION_OR_UPDATE: "documentAdditionOrUpdate", - DOCUMENT_DELETION: "documentDeletion", - DUMP_CREATION: "dumpCreation", - INDEX_CREATION: "indexCreation", - INDEX_DELETION: "indexDeletion", - INDEXES_SWAP: "indexSwap", - INDEX_UPDATE: "indexUpdate", - SETTINGS_UPDATE: "settingsUpdate", - SNAPSHOT_CREATION: "snapshotCreation", - TASK_CANCELATION: "taskCancelation", - TASK_DELETION: "taskDeletion", -} as const; - -export type TaskTypes = (typeof TaskTypes)[keyof typeof TaskTypes]; - -export type TasksQuery = { - indexUids?: string[]; - uids?: number[]; - types?: TaskTypes[]; - statuses?: TaskStatus[]; - canceledBy?: number[]; - beforeEnqueuedAt?: Date; - afterEnqueuedAt?: Date; - beforeStartedAt?: Date; - afterStartedAt?: Date; - beforeFinishedAt?: Date; - afterFinishedAt?: Date; - limit?: number; - from?: number; - /** - * If true, the tasks are returned in reverse order (requires Meilisearch - * 1.12.0 or later) - */ - reverse?: boolean; -}; - -export type CancelTasksQuery = Omit; - -export type DeleteTasksQuery = Omit; - -export type EnqueuedTaskObject = { - taskUid: number; - indexUid?: string; - status: TaskStatus; - type: TaskTypes; - enqueuedAt: string; - canceledBy: number; -}; - -export type TaskObject = Omit & { - uid: number; - /** The UID of the batch that the task belongs to (`null` for enqueued tasks) */ - batchUid: number | null; - details: { - // Number of documents sent - receivedDocuments?: number; - - // Number of documents successfully indexed/updated in Meilisearch - indexedDocuments?: number; - - // Number of deleted documents - deletedDocuments?: number; - - // Number of documents found on a batch-delete - providedIds?: number; - - // Primary key on index creation - primaryKey?: string; - - // Ranking rules on settings actions - rankingRules?: RankingRules; - - // Searchable attributes on settings actions - searchableAttributes?: SearchableAttributes; - - // Displayed attributes on settings actions - displayedAttributes?: DisplayedAttributes; - - // Filterable attributes on settings actions - filterableAttributes?: FilterableAttributes; - - // Sortable attributes on settings actions - sortableAttributes?: SortableAttributes; - - // Stop words on settings actions - stopWords?: StopWords; - - // Stop words on settings actions - synonyms?: Synonyms; - - // Distinct attribute on settings actions - distinctAttribute?: DistinctAttribute; - - // Object containing the payload originating the `indexSwap` task creation - swaps?: SwapIndexesParams; - - // Number of tasks that matched the originalQuery filter - matchedTasks?: number; - - // Number of tasks that were canceled - canceledTasks?: number; - - // Number of tasks that were deleted - deletedTasks?: number; - - // Query parameters used to filter the tasks - originalFilter?: string; - }; - error: MeiliSearchErrorResponse | null; - duration: string; - startedAt: string; - finishedAt: string; -}; - -export type SwapIndexesParams = { indexes: string[] }[]; - -type CursorResults = { - results: T[]; - limit: number; - from: number; - next: number; - total: number; -}; - -export type TasksResults = CursorResults; -export type TasksResultsObject = CursorResults; - -export type WaitOptions = { - timeOutMs?: number; - intervalMs?: number; -}; - -/* - ** BATCHES - */ - -/** - * Represents a batch operation object containing information about tasks - * processing - */ -export type BatchObject = { - /** Unique identifier for the batch */ - uid: number; - - /** Details about document processing */ - details: { - /** Number of documents received in the batch */ - receivedDocuments?: number; - /** Number of documents successfully indexed */ - indexedDocuments?: number; - /** Number of documents deleted in the batch */ - deletedDocuments?: number; - }; - - /** Progress and indexing step of the batch, null if the batch is finished */ - progress: null | { - /** An array of all the steps currently being processed */ - steps: { - /** - * A string representing the name of the current step NOT stable. Only use - * for debugging purposes. - */ - currentStep: string; - /** Number of finished tasks */ - finished: number; - /** Total number of tasks to finish before moving to the next step */ - total: number; - }[]; - /** Percentage of progression of all steps currently being processed */ - percentage: number; - }; - - /** Statistics about tasks within the batch */ - stats: { - /** Total number of tasks in the batch */ - totalNbTasks: number; - /** Count of tasks in each status */ - status: { - /** Number of successfully completed tasks */ - succeeded: number; - /** Number of failed tasks */ - failed: number; - /** Number of canceled tasks */ - canceled: number; - /** Number of tasks currently processing */ - processing: number; - /** Number of tasks waiting to be processed */ - enqueued: number; - }; - /** Count of tasks by type */ - types: Record; - /** Count of tasks by index UID */ - indexUids: Record; - }; - - /** Timestamp when the batch started processing (rfc3339 format) */ - startedAt: string; - /** Timestamp when the batch finished processing (rfc3339 format) */ - finishedAt: string; - /** Duration of batch processing */ - duration: string; -}; - -export type BatchesQuery = { - /** The batch should contain the specified task UIDs */ - uids?: number[]; - batchUids?: number[]; - types?: TaskTypes[]; - statuses?: TaskStatus[]; - indexUids?: string[]; - canceledBy?: number[]; - beforeEnqueuedAt?: Date; - afterEnqueuedAt?: Date; - beforeStartedAt?: Date; - afterStartedAt?: Date; - beforeFinishedAt?: Date; - afterFinishedAt?: Date; - limit?: number; - from?: number; -}; - -export type BatchesResults = CursorResults; -export type BatchesResultsObject = CursorResults; - /* *** HEALTH */ @@ -974,7 +735,7 @@ export type MeiliSearchErrorResponse = { link: string; }; -// @TODO: This doesn't seem to be up to date, and its usefullness comes into question. +// @TODO: This doesn't seem to be up to date, and its usefulness comes into question. export const ErrorStatusCode = { /** @see https://www.meilisearch.com/docs/reference/errors/error_codes#index_creation_failed */ INDEX_CREATION_FAILED: "index_creation_failed", @@ -1339,75 +1100,3 @@ export const ErrorStatusCode = { export type ErrorStatusCode = (typeof ErrorStatusCode)[keyof typeof ErrorStatusCode]; - -/** @see {@link TokenSearchRules} */ -export type TokenIndexRules = { filter?: Filter }; - -/** - * {@link https://www.meilisearch.com/docs/learn/security/tenant_token_reference#search-rules} - * - * @remarks - * Not well documented. - * @see `meilisearch_auth::SearchRules` at {@link https://github.com/meilisearch/meilisearch} - */ -export type TokenSearchRules = - | Record - | string[]; - -/** Options object for tenant token generation. */ -export type TenantTokenGeneratorOptions = { - /** API key used to sign the token. */ - apiKey: string; - /** - * The uid of the api key used as issuer of the token. - * - * @see {@link https://www.meilisearch.com/docs/learn/security/tenant_token_reference#api-key-uid} - */ - apiKeyUid: string; - /** - * Search rules that are applied to every search. - * - * @defaultValue `["*"]` - */ - searchRules?: TokenSearchRules; - /** - * {@link https://en.wikipedia.org/wiki/Unix_time | UNIX timestamp} or - * {@link Date} object at which the token expires. - * - * @see {@link https://www.meilisearch.com/docs/learn/security/tenant_token_reference#expiry-date} - */ - expiresAt?: number | Date; - /** - * Encryption algorithm used to sign the JWT. Supported values by Meilisearch - * are HS256, HS384, HS512. (HS[number] means HMAC using SHA-[number]) - * - * @defaultValue `"HS256"` - * @see {@link https://www.meilisearch.com/docs/learn/security/generate_tenant_token_scratch#prepare-token-header} - */ - algorithm?: `HS${256 | 384 | 512}`; - /** - * By default if a non-safe environment is detected, an error is thrown. - * Setting this to `true` skips environment detection. This is intended for - * server-side environments where detection fails or usage in a browser is - * intentional (Use at your own risk). - * - * @defaultValue `false` - */ - force?: boolean; -}; - -/** - * @see {@link https://www.meilisearch.com/docs/learn/security/tenant_token_reference | Tenant token payload reference} - * @see {@link https://github.com/meilisearch/meilisearch/blob/b21d7aedf9096539041362d438e973a18170f3fc/crates/meilisearch/src/extractors/authentication/mod.rs#L334-L340 | GitHub source code} - */ -export type TokenClaims = { - searchRules: TokenSearchRules; - exp?: number; - apiKeyUid: string; -}; - -/** JSON Web Token header. */ -export type TenantTokenHeader = { - alg: NonNullable; - typ: "JWT"; -}; diff --git a/tests/batch.test.ts b/tests/batch.test.ts index f2748c71a..42a1e95f9 100644 --- a/tests/batch.test.ts +++ b/tests/batch.test.ts @@ -18,21 +18,20 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: Get all batches`, async () => { const client = await getClient(permission); - const batches = await client.getBatches(); + const batches = await client.batches.getBatches(); expect(batches.results.length).toBeGreaterThan(0); }); test(`${permission} key: Get one batch`, async () => { const client = await getClient(permission); - const batches = await client.getBatches(); - const batch = await client.getBatch(batches.results[0].uid); + const batches = await client.batches.getBatches(); + const batch = await client.batches.getBatch(batches.results[0].uid); expect(batch.uid).toEqual(batches.results[0].uid); expect(batch.details).toBeDefined(); expect(batch.stats).toHaveProperty("totalNbTasks"); diff --git a/tests/client.test.ts b/tests/client.test.ts index 1e6237ce3..c1b5b5926 100644 --- a/tests/client.test.ts +++ b/tests/client.test.ts @@ -8,12 +8,8 @@ import { type MockInstance, beforeAll, } from "vitest"; -import type { Health, Version, Stats } from "../src/index.js"; -import { - ErrorStatusCode, - MeiliSearchRequestError, - TaskTypes, -} from "../src/index.js"; +import type { Health, Version, Stats, IndexSwap } from "../src/index.js"; +import { ErrorStatusCode, MeiliSearchRequestError } from "../src/index.js"; import { PACKAGE_VERSION } from "../src/package-version.js"; import { clearAllIndexes, @@ -261,8 +257,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( expect(health).toBe(true); - const task = await client.createIndex("test"); - await client.waitForTask(task.taskUid); + await client.createIndex("test").waitTask(); const { results } = await client.getIndexes(); @@ -283,8 +278,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( expect(health).toBe(true); - const task = await client.createIndex("test"); - await client.waitForTask(task.taskUid); + await client.createIndex("test").waitTask(); const { results } = await client.getIndexes(); @@ -292,10 +286,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const index = await client.getIndex("test"); - const { taskUid } = await index.addDocuments([ - { id: 1, title: "index_2" }, - ]); - await client.waitForTask(taskUid); + await index.addDocuments([{ id: 1, title: "index_2" }]).waitTask(); const { results: documents } = await index.getDocuments(); expect(documents.length).toBe(1); @@ -379,8 +370,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( describe("Test on indexes methods", () => { test(`${permission} key: create with no primary key`, async () => { const client = await getClient(permission); - const task = await client.createIndex(indexNoPk.uid); - await client.waitForTask(task.taskUid); + await client.createIndex(indexNoPk.uid).waitTask(); const newIndex = await client.getIndex(indexNoPk.uid); expect(newIndex).toHaveProperty("uid", indexNoPk.uid); @@ -399,10 +389,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: create with primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }); - await client.waitForTask(taskUid); + await client + .createIndex(indexPk.uid, { + primaryKey: indexPk.primaryKey, + }) + .waitTask(); const newIndex = await client.getIndex(indexPk.uid); @@ -422,8 +413,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: get all indexes when not empty`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexPk.uid).waitTask(); const { results } = await client.getRawIndexes(); const indexes = results.map((index) => index.uid); @@ -434,8 +424,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Get index that exists`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexPk.uid).waitTask(); const response = await client.getIndex(indexPk.uid); @@ -453,12 +442,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: update primary key`, async () => { const client = await getClient(permission); - const { taskUid: createTask } = await client.createIndex(indexPk.uid); - await client.waitForTask(createTask); - const { taskUid: updateTask } = await client.updateIndex(indexPk.uid, { - primaryKey: "newPrimaryKey", - }); - await client.waitForTask(updateTask); + await client.createIndex(indexPk.uid).waitTask(); + await client + .updateIndex(indexPk.uid, { + primaryKey: "newPrimaryKey", + }) + .waitTask(); const index = await client.getIndex(indexPk.uid); @@ -468,14 +457,16 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: update primary key that already exists`, async () => { const client = await getClient(permission); - const { taskUid: createTask } = await client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }); - await client.waitForTask(createTask); - const { taskUid: updateTask } = await client.updateIndex(indexPk.uid, { - primaryKey: "newPrimaryKey", - }); - await client.waitForTask(updateTask); + await client + .createIndex(indexPk.uid, { + primaryKey: indexPk.primaryKey, + }) + .waitTask(); + await client + .updateIndex(indexPk.uid, { + primaryKey: "newPrimaryKey", + }) + .waitTask(); const index = await client.getIndex(indexPk.uid); @@ -485,11 +476,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: delete index`, async () => { const client = await getClient(permission); - const { taskUid: createTask } = await client.createIndex(indexNoPk.uid); - await client.waitForTask(createTask); + await client.createIndex(indexNoPk.uid).waitTask(); - const { taskUid: deleteTask } = await client.deleteIndex(indexNoPk.uid); - await client.waitForTask(deleteTask); + await client.deleteIndex(indexNoPk.uid).waitTask(); const { results } = await client.getIndexes(); expect(results).toHaveLength(0); @@ -497,11 +486,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: create index with already existing uid should fail`, async () => { const client = await getClient(permission); - const { taskUid: firstCreate } = await client.createIndex(indexPk.uid); - await client.waitForTask(firstCreate); + await client.createIndex(indexPk.uid).waitTask(); - const { taskUid: secondCreate } = await client.createIndex(indexPk.uid); - const task = await client.waitForTask(secondCreate); + const task = await client.createIndex(indexPk.uid).waitTask(); expect(task.status).toBe("failed"); }); @@ -509,9 +496,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: delete index with uid that does not exist should fail`, async () => { const client = await getClient(permission); const index = client.index(indexNoPk.uid); - const { taskUid } = await index.delete(); - - const task = await client.waitForTask(taskUid); + const task = await index.delete().waitTask(); expect(task.status).toEqual("failed"); }); @@ -530,60 +515,48 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( await client .index(index.uid) .addDocuments([{ id: 1, title: `index_1` }]); - const { taskUid } = await client + await client .index(index2.uid) - .addDocuments([{ id: 1, title: "index_2" }]); - await client.waitForTask(taskUid); - const swaps = [ - { - indexes: [index.uid, index2.uid], - }, - ]; + .addDocuments([{ id: 1, title: "index_2" }]) + .waitTask(); + const swaps: IndexSwap[] = [{ indexes: [index.uid, index2.uid] }]; - const swapTask = await client.swapIndexes(swaps); - const resolvedTask = await client.waitForTask(swapTask.taskUid); + const resolvedTask = await client.swapIndexes(swaps).waitTask(); const docIndex1 = await client.index(index.uid).getDocument(1); const docIndex2 = await client.index(index2.uid).getDocument(1); expect(docIndex1.title).toEqual("index_2"); expect(docIndex2.title).toEqual("index_1"); - expect(resolvedTask.type).toEqual(TaskTypes.INDEXES_SWAP); - expect(resolvedTask.details.swaps).toEqual(swaps); + expect(resolvedTask.type).toEqual("indexSwap"); + expect(resolvedTask.details!.swaps).toEqual(swaps); }); test(`${permission} key: Swap two indexes with one that does not exist`, async () => { const client = await getClient(permission); - const { taskUid } = await client + await client .index(index2.uid) - .addDocuments([{ id: 1, title: "index_2" }]); + .addDocuments([{ id: 1, title: "index_2" }]) + .waitTask(); - await client.waitForTask(taskUid); - const swaps = [ - { - indexes: ["does_not_exist", index2.uid], - }, + const swaps: IndexSwap[] = [ + { indexes: ["does_not_exist", index2.uid] }, ]; - const swapTask = await client.swapIndexes(swaps); - const resolvedTask = await client.waitForTask(swapTask.taskUid); + const resolvedTask = await client.swapIndexes(swaps).waitTask(); - expect(resolvedTask.type).toEqual(TaskTypes.INDEXES_SWAP); + expect(resolvedTask.type).toEqual("indexSwap"); expect(resolvedTask.error?.code).toEqual( ErrorStatusCode.INDEX_NOT_FOUND, ); - expect(resolvedTask.details.swaps).toEqual(swaps); + expect(resolvedTask.details!.swaps).toEqual(swaps); }); // Should be fixed by rc1 test(`${permission} key: Swap two one index with itself`, async () => { const client = await getClient(permission); - const swaps = [ - { - indexes: [index.uid, index.uid], - }, - ]; + const swaps: IndexSwap[] = [{ indexes: [index.uid, index.uid] }]; await expect(client.swapIndexes(swaps)).rejects.toHaveProperty( "cause.code", diff --git a/tests/dictionary.test.ts b/tests/dictionary.test.ts index f1c853e0b..c4ca74a78 100644 --- a/tests/dictionary.test.ts +++ b/tests/dictionary.test.ts @@ -1,5 +1,4 @@ import { afterAll, expect, test, describe, beforeEach } from "vitest"; -import { EnqueuedTask } from "../src/enqueued-task.js"; import { clearAllIndexes, config, @@ -22,8 +21,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default dictionary`, async () => { @@ -36,12 +34,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update dictionary`, async () => { const client = await getClient(permission); const newDictionary = ["J. K.", "J. R. R."]; - const task: EnqueuedTask = await client - .index(index.uid) - .updateDictionary(newDictionary); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateDictionary(newDictionary).waitTask(); - const response: string[] = await client.index(index.uid).getDictionary(); + const response = await client.index(index.uid).getDictionary(); expect(response).toEqual(newDictionary); }); @@ -49,24 +44,18 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update dictionary with null value`, async () => { const client = await getClient(permission); const newDictionary = null; - const task: EnqueuedTask = await client - .index(index.uid) - .updateDictionary(newDictionary); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateDictionary(newDictionary).waitTask(); - const response: string[] = await client.index(index.uid).getDictionary(); + const response = await client.index(index.uid).getDictionary(); expect(response).toEqual([]); }); test(`${permission} key: Reset dictionary`, async () => { const client = await getClient(permission); - const task: EnqueuedTask = await client - .index(index.uid) - .resetDictionary(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetDictionary().waitTask(); - const response: string[] = await client.index(index.uid).getDictionary(); + const response = await client.index(index.uid).getDictionary(); expect(response).toEqual([]); }); diff --git a/tests/displayed_attributes.test.ts b/tests/displayed_attributes.test.ts index d3937ff75..b2779437d 100644 --- a/tests/displayed_attributes.test.ts +++ b/tests/displayed_attributes.test.ts @@ -1,5 +1,5 @@ import { afterAll, expect, test, describe, beforeEach } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -23,8 +23,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default displayed attributes`, async () => { @@ -37,10 +36,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update displayed attributes`, async () => { const client = await getClient(permission); const newDisplayedAttribute = ["title"]; - const task = await client + await client .index(index.uid) - .updateDisplayedAttributes(newDisplayedAttribute); - await client.index(index.uid).waitForTask(task.taskUid); + .updateDisplayedAttributes(newDisplayedAttribute) + .waitTask(); const response = await client.index(index.uid).getDisplayedAttributes(); @@ -50,10 +49,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update displayed attributes at null`, async () => { const client = await getClient(permission); - const task = await client - .index(index.uid) - .updateDisplayedAttributes(null); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateDisplayedAttributes(null).waitTask(); const response = await client.index(index.uid).getDisplayedAttributes(); @@ -63,8 +59,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Reset displayed attributes`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).resetDisplayedAttributes(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetDisplayedAttributes().waitTask(); const response = await client.index(index.uid).getDisplayedAttributes(); @@ -79,8 +74,7 @@ describe.each([{ permission: "Search" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get displayed attributes and be denied`, async () => { @@ -112,8 +106,7 @@ describe.each([{ permission: "No" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get displayed attributes and be denied`, async () => { diff --git a/tests/distinct_attribute.test.ts b/tests/distinct_attribute.test.ts index ca9cf12d5..ae9907ac7 100644 --- a/tests/distinct_attribute.test.ts +++ b/tests/distinct_attribute.test.ts @@ -1,5 +1,5 @@ import { afterAll, expect, test, describe, beforeEach } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -24,8 +24,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( await clearAllIndexes(config); const client = await getClient("master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default distinct attribute`, async () => { @@ -37,20 +36,19 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update distinct attribute`, async () => { const client = await getClient(permission); const newDistinctAttribute = "title"; - const task = await client + await client .index(index.uid) - .updateDistinctAttribute(newDistinctAttribute); - await client.index(index.uid).waitForTask(task.taskUid); + .updateDistinctAttribute(newDistinctAttribute) + .waitTask(); const response = await client.index(index.uid).getDistinctAttribute(); expect(response).toEqual(newDistinctAttribute); }); - test(`${permission} key: Update distinct attribute at null`, async () => { + test(`${permission} key: Update distinct attribute at undefined`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).updateDistinctAttribute(null); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateDistinctAttribute(null).waitTask(); const response = await client.index(index.uid).getDistinctAttribute(); @@ -59,8 +57,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Reset distinct attribute`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).resetDistinctAttribute(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetDistinctAttribute().waitTask(); const response = await client.index(index.uid).getDistinctAttribute(); diff --git a/tests/documents.test.ts b/tests/documents.test.ts index 5f7b62b1e..786ca2b97 100644 --- a/tests/documents.test.ts +++ b/tests/documents.test.ts @@ -1,10 +1,5 @@ import { afterAll, expect, test, describe, beforeEach } from "vitest"; -import { - ErrorStatusCode, - TaskStatus, - TaskTypes, - type ResourceResults, -} from "../src/types.js"; +import { ErrorStatusCode, type ResourceResults } from "../src/index.js"; import { clearAllIndexes, config, @@ -37,39 +32,31 @@ describe("Documents tests", () => { beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid: taskCreateNoPk } = await client.createIndex( - indexNoPk.uid, - ); - await client.waitForTask(taskCreateNoPk); - const { taskUid: taskCreateWithPk } = await client.createIndex( - indexPk.uid, - { + await client.createIndex(indexNoPk.uid).waitTask(); + await client + .createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }, - ); - await client.waitForTask(taskCreateWithPk); + }) + .waitTask(); }); test(`${permission} key: Add documents to uid with primary key in batch`, async () => { const client = await getClient(permission); - const tasks = await client + const tasks = client .index(indexPk.uid) .addDocumentsInBatches(dataset, 4); expect(tasks).toHaveLength(2); for (const task of tasks) { - const { type, status } = await client.waitForTask(task.taskUid); - expect(status).toBe(TaskStatus.TASK_SUCCEEDED); - expect(type).toBe(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE); + const { type, status } = await task.waitTask(); + assert.strictEqual(status, "succeeded"); + assert.strictEqual(type, "documentAdditionOrUpdate"); } }); test(`${permission} key: Get one document `, async () => { const client = await getClient(permission); - const { taskUid } = await client - .index(indexNoPk.uid) - .addDocuments(dataset); - await client.index(indexNoPk.uid).waitForTask(taskUid); + await client.index(indexNoPk.uid).addDocuments(dataset).waitTask(); const documentId = 1; const document = await client @@ -81,10 +68,7 @@ describe("Documents tests", () => { test(`${permission} key: Get one document with fields parameter`, async () => { const client = await getClient(permission); - const { taskUid } = await client - .index(indexNoPk.uid) - .addDocuments(dataset); - await client.index(indexNoPk.uid).waitForTask(taskUid); + await client.index(indexNoPk.uid).addDocuments(dataset).waitTask(); const documentId = 1; const document = await client @@ -109,10 +93,7 @@ describe("Documents tests", () => { test(`${permission} key: Get documents with array fields`, async () => { const client = await getClient(permission); - const { taskUid } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); const documents = await client.index(indexPk.uid).getDocuments({ fields: ["id"], @@ -132,10 +113,7 @@ describe("Documents tests", () => { test(`${permission} key: Get documents with pagination`, async () => { const client = await getClient(permission); - const { taskUid } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); const documents = await client.index(indexPk.uid).getDocuments({ limit: 1, @@ -150,15 +128,12 @@ describe("Documents tests", () => { test(`${permission} key: Get documents with filters`, async () => { const client = await getClient(permission); - const { taskUid: updateFilterableAttributesTaskUid } = await client + await client .index(indexPk.uid) - .updateFilterableAttributes(["id"]); - await client.waitForTask(updateFilterableAttributesTaskUid); + .updateFilterableAttributes(["id"]) + .waitTask(); - const { taskUid } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); const documents = await client.index(indexPk.uid).getDocuments({ filter: [["id = 1", "id = 2"]], @@ -192,10 +167,7 @@ describe("Documents tests", () => { test(`${permission} key: Get documents from index that has NO primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client - .index(indexNoPk.uid) - .addDocuments(dataset); - await client.index(indexNoPk.uid).waitForTask(taskUid); + await client.index(indexNoPk.uid).addDocuments(dataset).waitTask(); const documents = await client.index(indexNoPk.uid).getDocuments({ fields: "id", @@ -206,10 +178,7 @@ describe("Documents tests", () => { test(`${permission} key: Get documents from index that has a primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.index(indexPk.uid).waitForTask(taskUid); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); const documents = await client.index(indexPk.uid).getDocuments(); expect(documents.results.length).toEqual(dataset.length); @@ -219,10 +188,7 @@ describe("Documents tests", () => { const client = await getClient(permission); const adminKey = await getKey("Admin"); - const { taskUid } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.index(indexPk.uid).waitForTask(taskUid); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); // Get documents with POST const documentsPost = await client @@ -253,10 +219,7 @@ describe("Documents tests", () => { const client = await getClient(permission); const adminKey = await getKey("Admin"); - const { taskUid } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.index(indexPk.uid).waitForTask(taskUid); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); // Get documents with POST const documentsPost = await client @@ -285,17 +248,14 @@ describe("Documents tests", () => { test(`${permission} key: Replace documents from index that has NO primary key`, async () => { const client = await getClient(permission); - const { taskUid: addDocTask } = await client - .index(indexNoPk.uid) - .addDocuments(dataset); - await client.index(indexNoPk.uid).waitForTask(addDocTask); + await client.index(indexNoPk.uid).addDocuments(dataset).waitTask(); const id = 2; const title = "The Red And The Black"; - const task = await client + await client .index(indexNoPk.uid) - .addDocuments([{ id, title }]); - await client.index(indexNoPk.uid).waitForTask(task.taskUid); + .addDocuments([{ id, title }]) + .waitTask(); const response = await client.index(indexNoPk.uid).getDocument(id); expect(response).toHaveProperty("id", id); @@ -307,10 +267,10 @@ describe("Documents tests", () => { const id = 2; const title = "The Red And The Black"; - const task = await client + await client .index(indexPk.uid) - .addDocuments([{ id, title }]); - await client.index(indexPk.uid).waitForTask(task.taskUid); + .addDocuments([{ id, title }]) + .waitTask(); const response = await client.index(indexPk.uid).getDocument(id); expect(response).toHaveProperty("id", id); @@ -322,10 +282,10 @@ describe("Documents tests", () => { const id = 456; const title = "The Little Prince"; - const task = await client + await client .index(indexNoPk.uid) - .updateDocuments([{ id, title }]); - await client.index(indexNoPk.uid).waitForTask(task.taskUid); + .updateDocuments([{ id, title }]) + .waitTask(); const response = await client.index(indexNoPk.uid).getDocument(id); expect(response).toHaveProperty("id", id); @@ -336,10 +296,10 @@ describe("Documents tests", () => { const client = await getClient(permission); const id = 456; const title = "The Little Prince"; - const task = await client + await client .index(indexPk.uid) - .updateDocuments([{ id, title }]); - await client.index(indexPk.uid).waitForTask(task.taskUid); + .updateDocuments([{ id, title }]) + .waitTask(); const response = await client.index(indexPk.uid).getDocument(id); expect(response).toHaveProperty("id", id); @@ -349,10 +309,10 @@ describe("Documents tests", () => { test(`${permission} key: Partial update of a document`, async () => { const client = await getClient(permission); const id = 456; - const task = await client + await client .index(indexPk.uid) - .updateDocuments([{ id }]); - await client.index(indexPk.uid).waitForTask(task.taskUid); + .updateDocuments([{ id }]) + .waitTask(); const response = await client.index(indexPk.uid).getDocument(id); @@ -362,16 +322,14 @@ describe("Documents tests", () => { test(`${permission} key: Update document from index that has a primary key in batch`, async () => { const client = await getClient(permission); - const tasks = await client + const tasks = client .index(indexPk.uid) .updateDocumentsInBatches(dataset, 2); for (const EnqueuedTask of tasks) { - const task = await client - .index(indexPk.uid) - .waitForTask(EnqueuedTask.taskUid); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); - expect(task.type).toBe(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE); + const task = await EnqueuedTask.waitTask(); + assert.strictEqual(task.status, "succeeded"); + assert.strictEqual(task.type, "documentAdditionOrUpdate"); } expect(tasks).toHaveLength(4); }); @@ -380,34 +338,29 @@ describe("Documents tests", () => { const client = await getClient(permission); const partialDocument = { id: 1 }; - const tasks = await client + const tasks = client .index(indexPk.uid) .updateDocumentsInBatches([partialDocument], 2); for (const EnqueuedTask of tasks) { - const task = await client - .index(indexPk.uid) - .waitForTask(EnqueuedTask.taskUid); + const task = await EnqueuedTask.waitTask(); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); - expect(task.type).toBe(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE); + assert.strictEqual(task.status, "succeeded"); + assert.strictEqual(task.type, "documentAdditionOrUpdate"); } expect(tasks).toHaveLength(1); }); test(`${permission} key: Add document with update documents function from index that has NO primary key`, async () => { const client = await getClient(permission); - const { taskUid: addDocTask } = await client - .index(indexNoPk.uid) - .addDocuments(dataset); - await client.index(indexNoPk.uid).waitForTask(addDocTask); + await client.index(indexNoPk.uid).addDocuments(dataset).waitTask(); const id = 9; const title = "1984"; - const task = await client + await client .index(indexNoPk.uid) - .updateDocuments([{ id, title }]); - await client.index(indexNoPk.uid).waitForTask(task.taskUid); + .updateDocuments([{ id, title }]) + .waitTask(); const document = await client.index(indexNoPk.uid).getDocument(id); const documents = await client .index(indexNoPk.uid) @@ -420,16 +373,13 @@ describe("Documents tests", () => { test(`${permission} key: Add document with update documents function from index that has a primary key`, async () => { const client = await getClient(permission); - const { taskUid: addDocTask } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.index(indexPk.uid).waitForTask(addDocTask); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); const id = 9; const title = "1984"; - const task = await client + await client .index(indexPk.uid) - .updateDocuments([{ id, title }]); - await client.index(indexPk.uid).waitForTask(task.taskUid); + .updateDocuments([{ id, title }]) + .waitTask(); const document = await client.index(indexPk.uid).getDocument(id); const documents = await client.index(indexPk.uid).getDocuments(); @@ -446,10 +396,7 @@ describe("Documents tests", () => { title: "hello", _id: 1, }; - const { taskUid: addDocTask } = await client - .index(indexNoPk.uid) - .addDocuments([doc]); - await client.index(indexNoPk.uid).waitForTask(addDocTask); + await client.index(indexNoPk.uid).addDocuments([doc]).waitTask(); const index = await client.index(indexNoPk.uid).fetchInfo(); @@ -462,10 +409,7 @@ describe("Documents tests", () => { title: "hello", findmeid: 1, }; - const { taskUid: addDocTask } = await client - .index(indexNoPk.uid) - .addDocuments([doc]); - await client.index(indexNoPk.uid).waitForTask(addDocTask); + await client.index(indexNoPk.uid).addDocuments([doc]).waitTask(); const index = await client.index(indexNoPk.uid).fetchInfo(); @@ -479,10 +423,10 @@ describe("Documents tests", () => { id: 1, _id: 1, }; - const { taskUid: addDocTask } = await client + const task = await client .index(indexNoPk.uid) - .addDocuments([doc]); - const task = await client.index(indexNoPk.uid).waitForTask(addDocTask); + .addDocuments([doc]) + .waitTask(); const index = await client.index(indexNoPk.uid).fetchInfo(); expect(task.error?.code).toEqual( @@ -497,10 +441,10 @@ describe("Documents tests", () => { title: "hello", idfindme: 1, }; - const { taskUid: addDocTask } = await client + const task = await client .index(indexNoPk.uid) - .addDocuments([doc]); - const task = await client.index(indexNoPk.uid).waitForTask(addDocTask); + .addDocuments([doc]) + .waitTask(); const index = await client.index(indexNoPk.uid).fetchInfo(); expect(task.error?.code).toEqual( @@ -511,14 +455,10 @@ describe("Documents tests", () => { test(`${permission} key: Delete a document from index that has NO primary key`, async () => { const client = await getClient(permission); - const { taskUid: addDocTask } = await client - .index(indexNoPk.uid) - .addDocuments(dataset); - await client.index(indexNoPk.uid).waitForTask(addDocTask); + await client.index(indexNoPk.uid).addDocuments(dataset).waitTask(); const id = 9; - const task = await client.index(indexNoPk.uid).deleteDocument(id); - await client.index(indexNoPk.uid).waitForTask(task.taskUid); + await client.index(indexNoPk.uid).deleteDocument(id).waitTask(); const documents = await client .index(indexNoPk.uid) .getDocuments(); @@ -528,14 +468,10 @@ describe("Documents tests", () => { test(`${permission} key: Delete a document from index that has a primary key`, async () => { const client = await getClient(permission); - const { taskUid: addDocTask } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.index(indexPk.uid).waitForTask(addDocTask); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); const id = 9; - const task = await client.index(indexPk.uid).deleteDocument(id); - await client.index(indexPk.uid).waitForTask(task.taskUid); + await client.index(indexPk.uid).deleteDocument(id).waitTask(); const response = await client.index(indexPk.uid).getDocuments(); expect(response.results.length).toEqual(dataset.length); @@ -544,65 +480,52 @@ describe("Documents tests", () => { test(`${permission} key: Delete some documents with string filters`, async () => { const client = await getClient(permission); await client.index(indexPk.uid).updateFilterableAttributes(["id"]); - const { taskUid: addDocTask } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.index(indexPk.uid).waitForTask(addDocTask); - - const task = await client - .index(indexPk.uid) - .deleteDocuments({ filter: "id IN [1, 2]" }); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); const resolvedTask = await client .index(indexPk.uid) - .waitForTask(task.taskUid); + .deleteDocuments({ filter: "id IN [1, 2]" }) + .waitTask(); + const documents = await client.index(indexPk.uid).getDocuments(); - expect(resolvedTask.details.deletedDocuments).toEqual(2); + expect(resolvedTask.details?.deletedDocuments).toEqual(2); expect(documents.results.length).toEqual(dataset.length - 2); }); test(`${permission} key: Delete some documents with array filters`, async () => { const client = await getClient(permission); await client.index(indexPk.uid).updateFilterableAttributes(["id"]); - const { taskUid: addDocTask } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.index(indexPk.uid).waitForTask(addDocTask); - - const task = await client - .index(indexPk.uid) - .deleteDocuments({ filter: [["id = 1", "id = 2"]] }); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); const resolvedTask = await client .index(indexPk.uid) - .waitForTask(task.taskUid); + .deleteDocuments({ filter: [["id = 1", "id = 2"]] }) + .waitTask(); + const documents = await client.index(indexPk.uid).getDocuments(); - expect(resolvedTask.details.deletedDocuments).toEqual(2); + expect(resolvedTask.details?.deletedDocuments).toEqual(2); expect(documents.results.length).toEqual(dataset.length - 2); }); test(`${permission} key: Delete some documents from index that has NO primary key`, async () => { const client = await getClient(permission); - const { taskUid: addDocTask } = await client - .index(indexNoPk.uid) - .addDocuments(dataset); - await client.index(indexNoPk.uid).waitForTask(addDocTask); + await client.index(indexNoPk.uid).addDocuments(dataset).waitTask(); const ids = [1, 2]; - const task = await client.index(indexNoPk.uid).deleteDocuments(ids); const resolvedTask = await client .index(indexNoPk.uid) - .waitForTask(task.taskUid); + .deleteDocuments(ids) + .waitTask(); const documents = await client .index(indexNoPk.uid) .getDocuments(); const returnedIds = documents.results.map((x) => x.id); - expect(resolvedTask.details.deletedDocuments).toEqual(2); - expect(resolvedTask.details.providedIds).toEqual(2); + expect(resolvedTask.details?.deletedDocuments).toEqual(2); + expect(resolvedTask.details?.providedIds).toEqual(2); expect(documents.results.length).toEqual(dataset.length - 2); expect(returnedIds).not.toContain(ids[0]); expect(returnedIds).not.toContain(ids[1]); @@ -610,14 +533,10 @@ describe("Documents tests", () => { test(`${permission} key: Delete some documents from index that has a primary key`, async () => { const client = await getClient(permission); - const { taskUid: addDocTask } = await client - .index(indexPk.uid) - .addDocuments(dataset); - await client.index(indexPk.uid).waitForTask(addDocTask); + await client.index(indexPk.uid).addDocuments(dataset).waitTask(); const ids = [1, 2]; - const task = await client.index(indexPk.uid).deleteDocuments(ids); - await client.index(indexPk.uid).waitForTask(task.taskUid); + await client.index(indexPk.uid).deleteDocuments(ids).waitTask(); const documents = await client.index(indexPk.uid).getDocuments(); const returnedIds = documents.results.map((x) => x.id); @@ -628,8 +547,7 @@ describe("Documents tests", () => { test(`${permission} key: Delete some documents should trigger error with a hint on a MeilisearchApiError`, async () => { const client = await getClient(permission); - const task = await client.createIndex(indexPk.uid); - await client.waitForTask(task.taskUid); + await client.createIndex(indexPk.uid).waitTask(); await assert.rejects( client.index(indexPk.uid).deleteDocuments({ filter: "" }), @@ -651,8 +569,7 @@ describe("Documents tests", () => { test(`${permission} key: Delete all document from index that has NO primary key`, async () => { const client = await getClient(permission); - const task = await client.index(indexNoPk.uid).deleteAllDocuments(); - await client.index(indexNoPk.uid).waitForTask(task.taskUid); + await client.index(indexNoPk.uid).deleteAllDocuments().waitTask(); const documents = await client .index(indexNoPk.uid) @@ -662,8 +579,7 @@ describe("Documents tests", () => { test(`${permission} key: Delete all document from index that has a primary key`, async () => { const client = await getClient(permission); - const task = await client.index(indexPk.uid).deleteAllDocuments(); - await client.index(indexPk.uid).waitForTask(task.taskUid); + await client.index(indexPk.uid).deleteAllDocuments().waitTask(); const documents = await client.index(indexPk.uid).getDocuments(); expect(documents.results.length).toEqual(0); @@ -699,13 +615,12 @@ describe("Documents tests", () => { }, ]; const pkIndex = "update_pk"; - const { taskUid } = await client.createIndex(pkIndex); - await client.waitForTask(taskUid); + await client.createIndex(pkIndex).waitTask(); - const task = await client + await client .index(pkIndex) - .addDocuments(docs, { primaryKey: "unique" }); - await client.waitForTask(task.taskUid); + .addDocuments(docs, { primaryKey: "unique" }) + .waitTask(); const response = await client.index(pkIndex).getRawInfo(); expect(response).toHaveProperty("uid", pkIndex); @@ -720,10 +635,10 @@ describe("Documents tests", () => { }, ]; - const { taskUid } = await client + const { error } = await client .index(indexNoPk.uid) - .addDocuments(docs); - const { error } = await client.waitForTask(taskUid); + .addDocuments(docs) + .waitTask(); expect(error).toHaveProperty("code"); expect(error).toHaveProperty("link"); @@ -733,14 +648,16 @@ describe("Documents tests", () => { test(`${permission} key: Try to add documents from index with no primary key with NO valid primary key, task should fail`, async () => { const client = await getClient(permission); - const { taskUid } = await client.index(indexNoPk.uid).addDocuments([ - { - unique: 2, - title: "Le Rouge et le Noir", - }, - ]); + const task = await client + .index(indexNoPk.uid) + .addDocuments([ + { + unique: 2, + title: "Le Rouge et le Noir", + }, + ]) + .waitTask(); - const task = await client.waitForTask(taskUid); const index = await client.index(indexNoPk.uid).getRawInfo(); expect(index.uid).toEqual(indexNoPk.uid); @@ -753,9 +670,7 @@ describe("Documents tests", () => { const index = client.index<(typeof dataset)[number]>(indexPk.uid); const adminKey = await getKey("Admin"); - const { taskUid: updateFilterableAttributesTaskUid } = - await index.updateFilterableAttributes(["id"]); - await client.waitForTask(updateFilterableAttributesTaskUid); + await index.updateFilterableAttributes(["id"]).waitTask(); await fetch(`${HOST}/experimental-features`, { body: JSON.stringify({ editDocumentsByFunction: true }), @@ -766,18 +681,15 @@ describe("Documents tests", () => { method: "PATCH", }); - const { taskUid: addDocumentsTaskUid } = - await index.addDocuments(dataset); - await index.waitForTask(addDocumentsTaskUid); + await index.addDocuments(dataset).waitTask(); - const { taskUid: updateDocumentsByFunctionTaskUid } = - await index.updateDocumentsByFunction({ + await index + .updateDocumentsByFunction({ context: { ctx: "Harry" }, filter: "id = 4", function: "doc.comment = `Yer a wizard, ${context.ctx}!`", - }); - - await client.waitForTask(updateDocumentsByFunctionTaskUid); + }) + .waitTask(); const doc = await index.getDocument(4); diff --git a/tests/dump.test.ts b/tests/dump.test.ts index 07085f7bd..75c971533 100644 --- a/tests/dump.test.ts +++ b/tests/dump.test.ts @@ -1,5 +1,5 @@ -import { expect, test, describe, beforeEach } from "vitest"; -import { ErrorStatusCode, TaskStatus } from "../src/types.js"; +import { expect, test, describe, beforeEach, assert } from "vitest"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -17,11 +17,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { test(`${permission} key: create a new dump`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createDump(); + const taskResult = await client.createDump().waitTask(); - const taskResult = await client.waitForTask(taskUid); - - expect(taskResult).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); + assert.strictEqual(taskResult.status, "succeeded"); }); }, ); diff --git a/tests/embedders.test.ts b/tests/embedders.test.ts index 13ac89140..b41c60eb2 100644 --- a/tests/embedders.test.ts +++ b/tests/embedders.test.ts @@ -1,6 +1,5 @@ import { afterAll, expect, test, describe, beforeEach } from "vitest"; -import { EnqueuedTask } from "../src/enqueued-task.js"; -import type { Embedders } from "../src/types.js"; +import type { Embedders } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -57,13 +56,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( await clearAllIndexes(config); const client = await getClient(permission); - const task = await client.createIndex(index.uid); - await client.waitForTask(task.taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: Get default embedders`, async () => { const client = await getClient(permission); - const response: Embedders = await client.index(index.uid).getEmbedders(); + const response = await client.index(index.uid).getEmbedders(); expect(response).toEqual({}); }); @@ -81,13 +79,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( binaryQuantized: false, }, }; - const task: EnqueuedTask = await client - .index(index.uid) - .updateEmbedders(newEmbedder); - - await client.waitForTask(task.taskUid); + await client.index(index.uid).updateEmbedders(newEmbedder).waitTask(); - const response: Embedders = await client.index(index.uid).getEmbedders(); + const response = await client.index(index.uid).getEmbedders(); expect(response).toEqual(newEmbedder); expect(response).not.toHaveProperty("documentTemplateMaxBytes"); @@ -112,12 +106,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( binaryQuantized: false, }, }; - const task: EnqueuedTask = await client - .index(index.uid) - .updateEmbedders(newEmbedder); - await client.waitForTask(task.taskUid); + await client.index(index.uid).updateEmbedders(newEmbedder).waitTask(); - const response: Embedders = await client.index(index.uid).getEmbedders(); + const response = await client.index(index.uid).getEmbedders(); expect(response).toEqual({ default: { @@ -143,12 +134,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( binaryQuantized: false, }, }; - const task: EnqueuedTask = await client + await client .index(index.uid) - .updateEmbedders(newEmbedder); - await client.waitForTask(task.taskUid, { timeOutMs: 60_000 }); + .updateEmbedders(newEmbedder) + .waitTask({ timeout: 60_000 }); - const response: Embedders = await client.index(index.uid).getEmbedders(); + const response = await client.index(index.uid).getEmbedders(); expect(response).toEqual(newEmbedder); }); @@ -186,12 +177,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( binaryQuantized: false, }, }; - const task: EnqueuedTask = await client - .index(index.uid) - .updateEmbedders(newEmbedder); - await client.waitForTask(task.taskUid); + await client.index(index.uid).updateEmbedders(newEmbedder).waitTask(); - const response: Embedders = await client.index(index.uid).getEmbedders(); + const response = await client.index(index.uid).getEmbedders(); expect(response).toEqual({ default: { @@ -219,12 +207,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( binaryQuantized: false, }, }; - const task: EnqueuedTask = await client - .index(index.uid) - .updateEmbedders(newEmbedder); - await client.waitForTask(task.taskUid); + await client.index(index.uid).updateEmbedders(newEmbedder).waitTask(); - const response: Embedders = await client.index(index.uid).getEmbedders(); + const response = await client.index(index.uid).getEmbedders(); expect(response).toEqual({ default: { @@ -243,23 +228,18 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( dimensions: 512, }, }; - const task: EnqueuedTask = await client - .index(index.uid) - .updateEmbedders(newEmbedder); + await client.index(index.uid).updateEmbedders(newEmbedder).waitTask(); - await client.waitForTask(task.taskUid); - - const response: Embedders = await client.index(index.uid).getEmbedders(); + const response = await client.index(index.uid).getEmbedders(); expect(response).toEqual(newEmbedder); }); test(`${permission} key: Reset embedders`, async () => { const client = await getClient(permission); - const task: EnqueuedTask = await client.index(index.uid).resetEmbedders(); - await client.waitForTask(task.taskUid); + await client.index(index.uid).resetEmbedders().waitTask(); - const response: Embedders = await client.index(index.uid).getEmbedders(); + const response = await client.index(index.uid).getEmbedders(); expect(response).toEqual({}); }); @@ -267,13 +247,15 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: search (POST) with vectors`, async () => { const client = await getClient(permission); - const { taskUid } = await client.index(index.uid).updateEmbedders({ - default: { - source: "userProvided", - dimensions: 1, - }, - }); - await client.waitForTask(taskUid); + await client + .index(index.uid) + .updateEmbedders({ + default: { + source: "userProvided", + dimensions: 1, + }, + }) + .waitTask(); const response = await client.index(index.uid).search("", { vector: [1], @@ -294,13 +276,15 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: search (GET) with vectors`, async () => { const client = await getClient(permission); - const { taskUid } = await client.index(index.uid).updateEmbedders({ - default: { - source: "userProvided", - dimensions: 1, - }, - }); - await client.waitForTask(taskUid); + await client + .index(index.uid) + .updateEmbedders({ + default: { + source: "userProvided", + dimensions: 1, + }, + }) + .waitTask(); const response = await client.index(index.uid).searchGet("", { vector: [1], @@ -325,17 +309,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( dimensions: 3, }, }; - const { taskUid: updateEmbeddersTask }: EnqueuedTask = await client - .index(index.uid) - .updateEmbedders(newEmbedder); - - await client.waitForTask(updateEmbeddersTask); + await client.index(index.uid).updateEmbedders(newEmbedder).waitTask(); - const { taskUid: documentAdditionTask } = await client + await client .index(index.uid) - .addDocuments(datasetSimilarSearch); - - await client.waitForTask(documentAdditionTask); + .addDocuments(datasetSimilarSearch) + .waitTask(); const response = await client.index(index.uid).searchSimilarDocuments({ embedder: "manual", diff --git a/tests/env/browser/index.html b/tests/env/browser/index.html index 0117acbc3..933050d4b 100644 --- a/tests/env/browser/index.html +++ b/tests/env/browser/index.html @@ -23,11 +23,9 @@ host: 'http://localhost:7700', apiKey: 'masterKey', }) - const task = await client.createIndex(UID) - await client.waitForTask(task.taskUid) + await client.createIndex(UID).waitTask() - const documentTask = await client.index(UID).addDocuments([{ id: 1, title: "wonder woman" }]) - await client.waitForTask(documentTask.taskUid) + await client.index(UID).addDocuments([{ id: 1, title: "wonder woman" }]).waitTask() const index = await client.index(UID).getRawInfo() @@ -43,8 +41,7 @@ searchDiv.innerHTML = JSON.stringify(search) document.body.insertBefore(searchDiv, document.querySelector("#content")); - const deleteTask = await client.index(UID).delete() - await client.waitForTask(deleteTask.uid) + await client.index(UID).delete().waitTask() } catch (e) { console.error(e); } diff --git a/tests/env/express/public/headers.html b/tests/env/express/public/headers.html index 8ea4cb005..58d4a96e3 100644 --- a/tests/env/express/public/headers.html +++ b/tests/env/express/public/headers.html @@ -23,8 +23,7 @@ let error = 'NO ERRORS' try { - const task = await client.createIndex(UID) - await client.waitForTask(task.taskUid) + await client.createIndex(UID).waitTask() await fetch(`http://localhost:7700/indexes/${UID}/documents`, { method: 'POST', headers: { @@ -41,8 +40,7 @@ errorDiv.innerHTML = error document.body.insertBefore(errorDiv, document.querySelector("#content")); - const deleteTask = await client.index(UID).delete() - await client.waitForTask(deleteTask.taskUid) + await client.index(UID).delete().waitTask() })() diff --git a/tests/env/express/public/index.html b/tests/env/express/public/index.html index 7dda4eeb8..32dad5380 100644 --- a/tests/env/express/public/index.html +++ b/tests/env/express/public/index.html @@ -26,11 +26,9 @@ const UID = "testIndex" try { - const task = await client.createIndex(UID) - await client.waitForTask(task.taskUid) + await client.createIndex(UID).waitTask() - const documentTask = await client.index(UID).addDocuments([{ id: 1, title: "wonder woman" }]) - await client.waitForTask(documentTask.taskUid) + await client.index(UID).addDocuments([{ id: 1, title: "wonder woman" }]).waitTask() const index = await client.index(UID).getRawInfo() @@ -50,7 +48,6 @@ } searchDiv.innerHTML = content document.body.insertBefore(searchDiv, document.querySelector("#content")); - const deleteTask = await client.index(UID).delete() - await client.waitForTask(deleteTask.taskUid) + await client.index(UID).delete().waitTask() })() diff --git a/tests/env/node/getting_started.cjs b/tests/env/node/getting_started.cjs index 651101b27..f16d357c6 100644 --- a/tests/env/node/getting_started.cjs +++ b/tests/env/node/getting_started.cjs @@ -25,11 +25,7 @@ const { MeiliSearch } = require('../../../dist/cjs/index.cjs') 'id' ]) - let response = await index.addDocuments(dataset) - - console.log(response) // => { "updateId": 0 } - - await client.waitForTask(response.taskUid) + await index.addDocuments(dataset).waitTask() const search = await index.search('philoudelphia') console.log({ search, hit: search.hits }) diff --git a/tests/env/node/search_example.cjs b/tests/env/node/search_example.cjs index 51fbf8d83..ed84b227c 100644 --- a/tests/env/node/search_example.cjs +++ b/tests/env/node/search_example.cjs @@ -11,15 +11,13 @@ const indexUid = 'movies' const addDataset = async () => { await client.deleteIndex(indexUid) - const { taskUid } = await client.createIndex(indexUid) - await client.waitForTask(taskUid) + await client.createIndex(indexUid).waitTask() const index = client.index(indexUid) const documents = await index.getDocuments() if (documents.results.length === 0) { - const { taskUid } = await index.addDocuments(dataset) - await index.waitForTask(taskUid) + await index.addDocuments(dataset).waitTask() } } diff --git a/tests/env/typescript-node/src/index.ts b/tests/env/typescript-node/src/index.ts index 0ca8ecba5..495723c13 100644 --- a/tests/env/typescript-node/src/index.ts +++ b/tests/env/typescript-node/src/index.ts @@ -28,9 +28,8 @@ const client = new MeiliSearch(config) const indexUid = "movies" ;(async () => { - await client.deleteIndex(indexUid) - const { taskUid } = await client.createIndex(indexUid) - await client.waitForTask(taskUid) + await client.deleteIndex(indexUid).waitTask() + await client.createIndex(indexUid).waitTask() const index = client.index(indexUid) const indexes = await client.getRawIndexes() diff --git a/tests/errors.test.ts b/tests/errors.test.ts index dc0a8b9f0..f9596f98a 100644 --- a/tests/errors.test.ts +++ b/tests/errors.test.ts @@ -1,11 +1,6 @@ -import { expect, test, describe, beforeEach, vi } from "vitest"; -import { assert, MeiliSearch } from "./utils/meilisearch-test-utils.js"; -import { - MeiliSearchError, - MeiliSearchApiError, - MeiliSearchRequestError, - MeiliSearchTimeOutError, -} from "../src/errors/index.js"; +import { test, describe, beforeEach, vi } from "vitest"; +import { MeiliSearch, assert } from "./utils/meilisearch-test-utils.js"; +import { MeiliSearchRequestError } from "../src/index.js"; const mockedFetch = vi.fn(); globalThis.fetch = mockedFetch; @@ -21,38 +16,4 @@ describe("Test on updates", () => { const client = new MeiliSearch({ host: "http://localhost:9345" }); await assert.rejects(client.health(), MeiliSearchRequestError); }); - - test("MeiliSearchApiError can be compared with the instanceof operator", () => { - expect( - new MeiliSearchApiError(new Response(), { - message: "Some error", - code: "some_error", - type: "random_error", - link: "a link", - }) instanceof MeiliSearchApiError, - ).toEqual(true); - }); - - test("MeilisearchRequestError can be compared with the instanceof operator", async () => { - mockedFetch.mockRejectedValue(new Error("fake error message")); - - const client = new MeiliSearch({ host: "http://localhost:9345" }); - try { - await client.health(); - } catch (error) { - expect(error instanceof MeiliSearchRequestError).toEqual(true); - } - }); - - test("MeiliSearchError can be compared with the instanceof operator", () => { - expect(new MeiliSearchError("message") instanceof MeiliSearchError).toEqual( - true, - ); - }); - - test("MeiliSearchTimeOutError can be compared with the instanceof operator", () => { - expect( - new MeiliSearchTimeOutError("message") instanceof MeiliSearchTimeOutError, - ).toEqual(true); - }); }); diff --git a/tests/facet_search.test.ts b/tests/facet_search.test.ts index 46a1c686c..53e9b1f34 100644 --- a/tests/facet_search.test.ts +++ b/tests/facet_search.test.ts @@ -45,8 +45,7 @@ describe.each([ await client.index(index.uid).updateSettings({ filterableAttributes: newFilterableAttributes, }); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: basic facet value search`, async () => { diff --git a/tests/facet_search_settings.test.ts b/tests/facet_search_settings.test.ts index 9b3d1e115..d1bb67dbe 100644 --- a/tests/facet_search_settings.test.ts +++ b/tests/facet_search_settings.test.ts @@ -1,5 +1,5 @@ import { afterAll, expect, test, describe, beforeEach } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -23,8 +23,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get facetSearch settings on empty index`, async () => { @@ -37,10 +36,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Set facetSearch settings with dedicated endpoint on empty index`, async () => { const client = await getClient(permission); - const { taskUid } = await client - .index(index.uid) - .updateFacetSearch(false); - await client.index(index.uid).waitForTask(taskUid); + await client.index(index.uid).updateFacetSearch(false).waitTask(); const updatedSettings = await client.index(index.uid).getFacetSearch(); expect(updatedSettings).toBe(false); @@ -49,8 +45,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Reset facetSearch settings on an empty index`, async () => { const client = await getClient(permission); - const { taskUid } = await client.index(index.uid).resetFacetSearch(); - await client.index(index.uid).waitForTask(taskUid); + await client.index(index.uid).resetFacetSearch().waitTask(); const response = await client.index(index.uid).getFacetSearch(); expect(response).toMatchSnapshot(); @@ -64,8 +59,7 @@ describe.each([{ permission: "Search" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get facet search settings and be denied`, async () => { @@ -97,8 +91,7 @@ describe.each([{ permission: "No" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get facet search settings and be denied`, async () => { diff --git a/tests/faceting.test.ts b/tests/faceting.test.ts index 0aa7f0633..dc942b810 100644 --- a/tests/faceting.test.ts +++ b/tests/faceting.test.ts @@ -6,7 +6,7 @@ import { afterAll, beforeAll, } from "vitest"; -import { ErrorStatusCode, type Faceting } from "../src/types.js"; +import { ErrorStatusCode, type Faceting } from "../src/index.js"; import { clearAllIndexes, config, @@ -30,13 +30,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); - const { taskUid: docTask } = await client - .index(index.uid) - .addDocuments(dataset); - await client.waitForTask(docTask); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default faceting object`, async () => { @@ -53,8 +49,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( maxValuesPerFacet: 12, sortFacetValuesBy: { test: "count" }, }; - const task = await client.index(index.uid).updateFaceting(newFaceting); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateFaceting(newFaceting).waitTask(); const response = await client.index(index.uid).getFaceting(); @@ -63,10 +58,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update faceting at null`, async () => { const client = await getClient(permission); - const task = await client + await client .index(index.uid) - .updateFaceting({ maxValuesPerFacet: null }); - await client.index(index.uid).waitForTask(task.taskUid); + .updateFaceting({ maxValuesPerFacet: null }) + .waitTask(); const response = await client.index(index.uid).getFaceting(); @@ -77,15 +72,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const client = await getClient(permission); await client .index(index.uid) - .waitForTask( - ( - await client - .index(index.uid) - .updateFaceting({ maxValuesPerFacet: 12 }) - ).taskUid, - ); - const task = await client.index(index.uid).resetFaceting(); - await client.index(index.uid).waitForTask(task.taskUid); + .updateFaceting({ maxValuesPerFacet: 12 }) + .waitTask(); + + await client.index(index.uid).resetFaceting().waitTask(); const response = await client.index(index.uid).getFaceting(); @@ -99,8 +89,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get faceting and be denied`, async () => { @@ -129,8 +118,7 @@ describe.each([{ permission: "Search" }])( describe.each([{ permission: "No" }])("Test on faceting", ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get faceting and be denied`, async () => { @@ -182,7 +170,7 @@ describe.each([ const client = new MeiliSearch({ host }); const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateFaceting({ maxValuesPerFacet: null }), + client.index(index.uid).updateFaceting({ maxValuesPerFacet: undefined }), ).rejects.toHaveProperty( "message", `Request to ${strippedHost}/${route} has failed`, diff --git a/tests/filterable_attributes.test.ts b/tests/filterable_attributes.test.ts index f951e96f7..79325ddff 100644 --- a/tests/filterable_attributes.test.ts +++ b/tests/filterable_attributes.test.ts @@ -1,5 +1,5 @@ import { expect, test, describe, beforeEach, afterAll } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -22,57 +22,44 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default attributes for filtering`, async () => { const client = await getClient(permission); - const response: string[] = await client - .index(index.uid) - .getFilterableAttributes(); + const response = await client.index(index.uid).getFilterableAttributes(); - expect(response.sort()).toEqual([]); + expect(response?.sort()).toEqual([]); }); test(`${permission} key: Update attributes for filtering`, async () => { const client = await getClient(permission); const newFilterableAttributes = ["genre"]; - const task = await client + await client .index(index.uid) - .updateFilterableAttributes(newFilterableAttributes); - await client.index(index.uid).waitForTask(task.taskUid); + .updateFilterableAttributes(newFilterableAttributes) + .waitTask(); - const response: string[] = await client - .index(index.uid) - .getFilterableAttributes(); + const response = await client.index(index.uid).getFilterableAttributes(); expect(response).toEqual(newFilterableAttributes); }); test(`${permission} key: Update attributes for filtering at null`, async () => { const client = await getClient(permission); - const task = await client - .index(index.uid) - .updateFilterableAttributes(null); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateFilterableAttributes(null).waitTask(); - const response: string[] = await client - .index(index.uid) - .getFilterableAttributes(); + const response = await client.index(index.uid).getFilterableAttributes(); - expect(response.sort()).toEqual([]); + expect(response?.sort()).toEqual([]); }); test(`${permission} key: Reset attributes for filtering`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).resetFilterableAttributes(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetFilterableAttributes().waitTask(); - const response: string[] = await client - .index(index.uid) - .getFilterableAttributes(); + const response = await client.index(index.uid).getFilterableAttributes(); - expect(response.sort()).toEqual([]); + expect(response?.sort()).toEqual([]); }); }, ); @@ -82,8 +69,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get attributes for filtering and be denied`, async () => { @@ -114,8 +100,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get attributes for filtering and be denied`, async () => { diff --git a/tests/get_search.test.ts b/tests/get_search.test.ts index fd9243a34..3a6771b1d 100644 --- a/tests/get_search.test.ts +++ b/tests/get_search.test.ts @@ -1,6 +1,5 @@ import { expect, test, describe, afterAll, beforeAll } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; -import { EnqueuedTask } from "../src/enqueued-task.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -85,24 +84,19 @@ describe.each([ beforeAll(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid: task1 } = await client.createIndex(index.uid); - await client.waitForTask(task1); - const { taskUid: task2 } = await client.createIndex(emptyIndex.uid); - await client.waitForTask(task2); + await client.createIndex(index.uid).waitTask(); + await client.createIndex(emptyIndex.uid).waitTask(); const newFilterableAttributes = ["genre", "title", "id", "author"]; - const { taskUid: task3 }: EnqueuedTask = await client + await client .index(index.uid) .updateSettings({ filterableAttributes: newFilterableAttributes, sortableAttributes: ["id"], - }); - await client.waitForTask(task3); + }) + .waitTask(); - const { taskUid: task4 } = await client - .index(index.uid) - .addDocuments(dataset); - await client.waitForTask(task4); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Basic search`, async () => { @@ -552,8 +546,7 @@ describe.each([ test(`${permission} key: Try to search on deleted index and fail`, async () => { const client = await getClient(permission); const masterClient = await getClient("Master"); - const { taskUid } = await masterClient.index(index.uid).delete(); - await masterClient.waitForTask(taskUid); + await masterClient.index(index.uid).delete().waitTask(); await expect( client.index(index.uid).searchGet("prince"), ).rejects.toHaveProperty("cause.code", ErrorStatusCode.INDEX_NOT_FOUND); diff --git a/tests/index.test.ts b/tests/index.test.ts index 7e9d70af5..faea55881 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -1,5 +1,5 @@ import { expect, test, describe, beforeEach, afterAll } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -16,9 +16,7 @@ const indexPk = { primaryKey: "id", }; -afterAll(async () => { - return clearAllIndexes(config); -}); +afterAll(() => clearAllIndexes(config)); describe.each([{ permission: "Master" }, { permission: "Admin" }])( "Test on indexes w/ master and admin key", @@ -29,8 +27,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: create index with NO primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexNoPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexNoPk.uid).waitTask(); const newIndex = await client.getIndex(indexNoPk.uid); @@ -47,10 +44,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: create index with primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }); - await client.waitForTask(taskUid); + await client + .createIndex(indexPk.uid, { + primaryKey: indexPk.primaryKey, + }) + .waitTask(); const newIndex = await client.getIndex(indexPk.uid); @@ -67,8 +65,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Get raw index that exists`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexPk.uid).waitTask(); const response = await client.getRawIndex(indexPk.uid); @@ -77,8 +74,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Get all indexes in Index instances`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexPk.uid).waitTask(); const { results } = await client.getRawIndexes(); @@ -104,10 +100,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Get raw index info through client with primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }); - await client.waitForTask(taskUid); + await client + .createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey }) + .waitTask(); const response = await client.getRawIndex(indexPk.uid); @@ -117,8 +112,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Get raw index info through client with NO primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexNoPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexNoPk.uid).waitTask(); const response = await client.getRawIndex(indexNoPk.uid); @@ -128,10 +122,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Get raw index info with primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }); - await client.waitForTask(taskUid); + await client + .createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey }) + .waitTask(); const response = await client.index(indexPk.uid).getRawInfo(); @@ -141,8 +134,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Get raw index info with NO primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexNoPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexNoPk.uid).waitTask(); const response = await client.index(indexNoPk.uid).getRawInfo(); @@ -152,10 +144,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: fetch index with primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }); - await client.waitForTask(taskUid); + await client + .createIndex(indexPk.uid, { + primaryKey: indexPk.primaryKey, + }) + .waitTask(); const index = client.index(indexPk.uid); const response = await index.fetchInfo(); @@ -166,10 +159,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: fetch primary key on an index with primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }); - await client.waitForTask(taskUid); + await client + .createIndex(indexPk.uid, { + primaryKey: indexPk.primaryKey, + }) + .waitTask(); const index = client.index(indexPk.uid); const response: string | undefined = await index.fetchPrimaryKey(); @@ -179,8 +173,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: fetch primary key on an index with NO primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexNoPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexNoPk.uid).waitTask(); const index = client.index(indexNoPk.uid); const response: string | undefined = await index.fetchPrimaryKey(); @@ -190,10 +183,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: fetch index with primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }); - await client.waitForTask(taskUid); + await client + .createIndex(indexPk.uid, { + primaryKey: indexPk.primaryKey, + }) + .waitTask(); const index = client.index(indexPk.uid); const response = await index.fetchInfo(); @@ -204,8 +198,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: fetch index with NO primary key`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexNoPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexNoPk.uid).waitTask(); const index = client.index(indexNoPk.uid); const response = await index.fetchInfo(); @@ -216,10 +209,8 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: get all indexes`, async () => { const client = await getClient(permission); - const task1 = await client.createIndex(indexNoPk.uid); - const task2 = await client.createIndex(indexPk.uid); - await client.waitForTask(task1.taskUid); - await client.waitForTask(task2.taskUid); + await client.createIndex(indexNoPk.uid).waitTask(); + await client.createIndex(indexPk.uid).waitTask(); const indexes = await client.getIndexes(); @@ -228,10 +219,8 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: get all indexes with filters`, async () => { const client = await getClient(permission); - const task1 = await client.createIndex(indexNoPk.uid); - const task2 = await client.createIndex(indexPk.uid); - await client.waitForTask(task1.taskUid); - await client.waitForTask(task2.taskUid); + await client.createIndex(indexNoPk.uid).waitTask(); + await client.createIndex(indexPk.uid).waitTask(); const indexes = await client.getIndexes({ limit: 1, offset: 1 }); @@ -241,12 +230,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: update primary key on an index that has no primary key already`, async () => { const client = await getClient(permission); - const { taskUid: createTask } = await client.createIndex(indexNoPk.uid); - const { taskUid: updateTask } = await client.index(indexNoPk.uid).update({ - primaryKey: "newPrimaryKey", - }); - await client.waitForTask(createTask); - await client.waitForTask(updateTask); + await client.createIndex(indexNoPk.uid).waitTask(); + await client + .index(indexNoPk.uid) + .update({ primaryKey: "newPrimaryKey" }) + .waitTask(); const index = await client.getIndex(indexNoPk.uid); @@ -256,12 +244,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: update primary key on an index that has NO primary key already through client`, async () => { const client = await getClient(permission); - const { taskUid: createTask } = await client.createIndex(indexNoPk.uid); - const { taskUid: updateTask } = await client.updateIndex(indexNoPk.uid, { - primaryKey: indexPk.primaryKey, - }); - await client.waitForTask(createTask); - await client.waitForTask(updateTask); + await client.createIndex(indexNoPk.uid).waitTask(); + await client + .updateIndex(indexNoPk.uid, { + primaryKey: indexPk.primaryKey, + }) + .waitTask(); const index = await client.getIndex(indexNoPk.uid); @@ -271,14 +259,16 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: update primary key on an index that has already a primary key and fail through client`, async () => { const client = await getClient(permission); - const { taskUid: createTask } = await client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }); - const { taskUid: updateTask } = await client.updateIndex(indexPk.uid, { - primaryKey: "newPrimaryKey", - }); - await client.waitForTask(createTask); - await client.waitForTask(updateTask); + await client + .createIndex(indexPk.uid, { + primaryKey: indexPk.primaryKey, + }) + .waitTask(); + await client + .updateIndex(indexPk.uid, { + primaryKey: "newPrimaryKey", + }) + .waitTask(); const index = await client.getIndex(indexPk.uid); @@ -288,14 +278,13 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: update primary key on an index that has already a primary key and fail`, async () => { const client = await getClient(permission); - const { taskUid: createTask } = await client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }); - const { taskUid: updateTask } = await client.index(indexPk.uid).update({ - primaryKey: "newPrimaryKey", - }); - await client.waitForTask(createTask); - await client.waitForTask(updateTask); + await client + .createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey }) + .waitTask(); + await client + .index(indexPk.uid) + .update({ primaryKey: "newPrimaryKey" }) + .waitTask(); const index = await client.getIndex(indexPk.uid); @@ -305,12 +294,8 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: delete index`, async () => { const client = await getClient(permission); - const { taskUid: createTask } = await client.createIndex(indexNoPk.uid); - const { taskUid: deleteTask } = await client - .index(indexNoPk.uid) - .delete(); - await client.waitForTask(createTask); - await client.waitForTask(deleteTask); + await client.createIndex(indexNoPk.uid).waitTask(); + await client.index(indexNoPk.uid).delete().waitTask(); const { results } = await client.getIndexes(); @@ -320,8 +305,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: delete index using client`, async () => { const client = await getClient(permission); await client.createIndex(indexPk.uid); - const { taskUid } = await client.deleteIndex(indexPk.uid); - await client.waitForTask(taskUid); + await client.deleteIndex(indexPk.uid).waitTask(); const { results } = await client.getIndexes(); @@ -348,17 +332,14 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: delete index with uid that does not exist should fail`, async () => { const client = await getClient(permission); const index = client.index(indexNoPk.uid); - const { taskUid } = await index.delete(); - - const task = await client.waitForTask(taskUid); + const task = await index.delete().waitTask(); expect(task.status).toBe("failed"); }); test(`${permission} key: get stats of an index`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexNoPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexNoPk.uid).waitTask(); const response = await client.index(indexNoPk.uid).getStats(); @@ -373,8 +354,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Get updatedAt and createdAt through fetch info`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexPk.uid).waitTask(); const index = await client.index(indexPk.uid).fetchInfo(); @@ -384,8 +364,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Get updatedAt and createdAt index through getRawInfo`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid); - await client.waitForTask(taskUid); + await client.createIndex(indexPk.uid).waitTask(); const index = client.index(indexPk.uid); diff --git a/tests/keys.test.ts b/tests/keys.test.ts index e054ad18f..a1e305d07 100644 --- a/tests/keys.test.ts +++ b/tests/keys.test.ts @@ -1,6 +1,6 @@ import { expect, test, describe, beforeEach, afterAll } from "vitest"; import { MeiliSearch } from "../src/index.js"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -137,10 +137,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const newClient = new MeiliSearch({ host: HOST, apiKey: key.key }); await newClient.createIndex("wildcard_keys_permission"); // test index creation - const taskInfo = await newClient + const task = await newClient .index("wildcard_keys_permission") - .addDocuments([{ id: 1 }]); // test document addition - const task = await newClient.waitForTask(taskInfo.taskUid); // test fetching of tasks + .addDocuments([{ id: 1 }]) + .waitTask(); // test document addition expect(key).toBeDefined(); expect(task.status).toBe("succeeded"); diff --git a/tests/localized_attributes.test.ts b/tests/localized_attributes.test.ts index 164f35dc8..963f406be 100644 --- a/tests/localized_attributes.test.ts +++ b/tests/localized_attributes.test.ts @@ -6,7 +6,10 @@ import { expect, test, } from "vitest"; -import { ErrorStatusCode, type LocalizedAttributes } from "../src/types.js"; +import { + ErrorStatusCode, + type LocalizedAttributes, +} from "../src/types/index.js"; import { clearAllIndexes, config, @@ -32,8 +35,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default localizedAttributes settings`, async () => { @@ -48,10 +50,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const newLocalizedAttributes: LocalizedAttributes = [ { attributePatterns: ["title"], locales: ["eng"] }, ]; - const task = await client + await client .index(index.uid) - .updateLocalizedAttributes(newLocalizedAttributes); - await client.waitForTask(task.taskUid); + .updateLocalizedAttributes(newLocalizedAttributes) + .waitTask(); const response = await client.index(index.uid).getLocalizedAttributes(); @@ -61,10 +63,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update localizedAttributes to null`, async () => { const client = await getClient(permission); const newLocalizedAttributes = null; - const task = await client + await client .index(index.uid) - .updateLocalizedAttributes(newLocalizedAttributes); - await client.index(index.uid).waitForTask(task.taskUid); + .updateLocalizedAttributes(newLocalizedAttributes) + .waitTask(); const response = await client.index(index.uid).getLocalizedAttributes(); @@ -88,12 +90,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Reset localizedAttributes`, async () => { const client = await getClient(permission); const newLocalizedAttributes: LocalizedAttributes = []; - const updateTask = await client + await client .index(index.uid) - .updateLocalizedAttributes(newLocalizedAttributes); - await client.waitForTask(updateTask.taskUid); - const task = await client.index(index.uid).resetLocalizedAttributes(); - await client.waitForTask(task.taskUid); + .updateLocalizedAttributes(newLocalizedAttributes) + .waitTask(); + await client.index(index.uid).resetLocalizedAttributes().waitTask(); const response = await client.index(index.uid).getLocalizedAttributes(); @@ -107,8 +108,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get localizedAttributes and be denied`, async () => { @@ -139,8 +139,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get localizedAttributes and be denied`, async () => { diff --git a/tests/non_separator_tokens.test.ts b/tests/non_separator_tokens.test.ts index 78518bb91..28c9dae82 100644 --- a/tests/non_separator_tokens.test.ts +++ b/tests/non_separator_tokens.test.ts @@ -1,5 +1,4 @@ import { expect, test, describe, beforeEach, afterAll } from "vitest"; -import { EnqueuedTask } from "../src/enqueued-task.js"; import { clearAllIndexes, config, @@ -22,15 +21,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default non separator tokens`, async () => { const client = await getClient(permission); - const response: string[] = await client - .index(index.uid) - .getNonSeparatorTokens(); + const response = await client.index(index.uid).getNonSeparatorTokens(); expect(response).toEqual([]); }); @@ -38,14 +34,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update non separator tokens`, async () => { const client = await getClient(permission); const newNonSeparatorTokens = ["&sep", "/", "|"]; - const task: EnqueuedTask = await client + await client .index(index.uid) - .updateNonSeparatorTokens(newNonSeparatorTokens); - await client.index(index.uid).waitForTask(task.taskUid); + .updateNonSeparatorTokens(newNonSeparatorTokens) + .waitTask(); - const response: string[] = await client - .index(index.uid) - .getNonSeparatorTokens(); + const response = await client.index(index.uid).getNonSeparatorTokens(); expect(response).toEqual(newNonSeparatorTokens); }); @@ -53,28 +47,21 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update non separator tokens with null value`, async () => { const client = await getClient(permission); const newNonSeparatorTokens = null; - const task: EnqueuedTask = await client + await client .index(index.uid) - .updateNonSeparatorTokens(newNonSeparatorTokens); - await client.index(index.uid).waitForTask(task.taskUid); + .updateNonSeparatorTokens(newNonSeparatorTokens) + .waitTask(); - const response: string[] = await client - .index(index.uid) - .getNonSeparatorTokens(); + const response = await client.index(index.uid).getNonSeparatorTokens(); expect(response).toEqual([]); }); test(`${permission} key: Reset NonSeparator tokens`, async () => { const client = await getClient(permission); - const task: EnqueuedTask = await client - .index(index.uid) - .resetNonSeparatorTokens(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetNonSeparatorTokens().waitTask(); - const response: string[] = await client - .index(index.uid) - .getNonSeparatorTokens(); + const response = await client.index(index.uid).getNonSeparatorTokens(); expect(response).toEqual([]); }); diff --git a/tests/pagination.test.ts b/tests/pagination.test.ts index 48e3dfda2..f8736bf53 100644 --- a/tests/pagination.test.ts +++ b/tests/pagination.test.ts @@ -6,7 +6,7 @@ afterAll, beforeAll, } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -30,8 +30,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default pagination settings`, async () => { @@ -46,10 +45,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const newPagination = { maxTotalHits: 100, }; - const task = await client - .index(index.uid) - .updatePagination(newPagination); - await client.waitForTask(task.taskUid); + await client.index(index.uid).updatePagination(newPagination).waitTask(); const response = await client.index(index.uid).getPagination(); @@ -61,10 +57,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const newPagination = { maxTotalHits: null, }; - const task = await client - .index(index.uid) - .updatePagination(newPagination); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updatePagination(newPagination).waitTask(); const response = await client.index(index.uid).getPagination(); @@ -76,12 +69,8 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const newPagination = { maxTotalHits: 100, }; - const updateTask = await client - .index(index.uid) - .updatePagination(newPagination); - await client.waitForTask(updateTask.taskUid); - const task = await client.index(index.uid).resetPagination(); - await client.waitForTask(task.taskUid); + await client.index(index.uid).updatePagination(newPagination).waitTask(); + await client.index(index.uid).resetPagination().waitTask(); const response = await client.index(index.uid).getPagination(); @@ -95,8 +84,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get pagination and be denied`, async () => { @@ -127,8 +115,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get pagination and be denied`, async () => { diff --git a/tests/prefix_search_settings.test.ts b/tests/prefix_search_settings.test.ts index cf6fdd7e2..77685c5fc 100644 --- a/tests/prefix_search_settings.test.ts +++ b/tests/prefix_search_settings.test.ts @@ -1,5 +1,5 @@ import { afterAll, expect, test, describe, beforeEach } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -23,8 +23,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get prefixSearch settings on empty index`, async () => { @@ -37,10 +36,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Set prefixSearch settings with dedicated endpoint on empty index`, async () => { const client = await getClient(permission); - const { taskUid } = await client - .index(index.uid) - .updatePrefixSearch("disabled"); - await client.index(index.uid).waitForTask(taskUid); + await client.index(index.uid).updatePrefixSearch("disabled").waitTask(); const updatedSettings = await client.index(index.uid).getPrefixSearch(); expect(updatedSettings).toBe("disabled"); @@ -49,8 +45,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Reset prefixSearch settings on an empty index`, async () => { const client = await getClient(permission); - const { taskUid } = await client.index(index.uid).resetPrefixSearch(); - await client.index(index.uid).waitForTask(taskUid); + await client.index(index.uid).resetPrefixSearch().waitTask(); const response = await client.index(index.uid).getPrefixSearch(); expect(response).toMatchSnapshot(); @@ -64,8 +59,7 @@ describe.each([{ permission: "Search" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get prefix search settings and be denied`, async () => { @@ -97,8 +91,7 @@ describe.each([{ permission: "No" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get prefix search settings and be denied`, async () => { diff --git a/tests/proximity_precision.test.ts b/tests/proximity_precision.test.ts index 1a73d4eb9..8500ca3fd 100644 --- a/tests/proximity_precision.test.ts +++ b/tests/proximity_precision.test.ts @@ -1,5 +1,4 @@ import { afterAll, describe, test, beforeEach, expect } from "vitest"; -import { EnqueuedTask } from "../src/enqueued-task.js"; import { clearAllIndexes, config, @@ -22,15 +21,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default proximity precision`, async () => { const client = await getClient(permission); - const response: string = await client - .index(index.uid) - .getProximityPrecision(); + const response = await client.index(index.uid).getProximityPrecision(); expect(response).toEqual("byWord"); }); @@ -38,14 +34,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update proximity precision with 'byAttribute' value`, async () => { const client = await getClient(permission); const newProximityPrecision = "byAttribute"; - const task: EnqueuedTask = await client + await client .index(index.uid) - .updateProximityPrecision(newProximityPrecision); - await client.index(index.uid).waitForTask(task.taskUid); + .updateProximityPrecision(newProximityPrecision) + .waitTask(); - const response: string = await client - .index(index.uid) - .getProximityPrecision(); + const response = await client.index(index.uid).getProximityPrecision(); expect(response).toEqual(newProximityPrecision); }); @@ -53,28 +47,21 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update proximity precision with 'byWord' value`, async () => { const client = await getClient(permission); const newProximityPrecision = "byWord"; - const task: EnqueuedTask = await client + await client .index(index.uid) - .updateProximityPrecision(newProximityPrecision); - await client.index(index.uid).waitForTask(task.taskUid); + .updateProximityPrecision(newProximityPrecision) + .waitTask(); - const response: string = await client - .index(index.uid) - .getProximityPrecision(); + const response = await client.index(index.uid).getProximityPrecision(); expect(response).toEqual(newProximityPrecision); }); test(`${permission} key: Reset proximity precision`, async () => { const client = await getClient(permission); - const task: EnqueuedTask = await client - .index(index.uid) - .resetProximityPrecision(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetProximityPrecision().waitTask(); - const response: string = await client - .index(index.uid) - .getProximityPrecision(); + const response = await client.index(index.uid).getProximityPrecision(); expect(response).toEqual("byWord"); }); diff --git a/tests/ranking_rules.test.ts b/tests/ranking_rules.test.ts index 42f4951f3..5025ea2c0 100644 --- a/tests/ranking_rules.test.ts +++ b/tests/ranking_rules.test.ts @@ -1,6 +1,5 @@ import { expect, test, describe, beforeEach, afterAll } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; -import { EnqueuedTask } from "../src/enqueued-task.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -33,57 +32,42 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default ranking rules`, async () => { const client = await getClient(permission); - const response: string[] = await client - .index(index.uid) - .getRankingRules(); + const response = await client.index(index.uid).getRankingRules(); expect(response).toEqual(defaultRankingRules); }); test(`${permission} key: Update ranking rules`, async () => { const client = await getClient(permission); const newRankingRules = ["title:asc", "typo", "description:desc"]; - const task: EnqueuedTask = await client + await client .index(index.uid) - .updateRankingRules(newRankingRules); - await client.index(index.uid).waitForTask(task.taskUid); + .updateRankingRules(newRankingRules) + .waitTask(); - const response: string[] = await client - .index(index.uid) - .getRankingRules(); + const response = await client.index(index.uid).getRankingRules(); expect(response).toEqual(newRankingRules); }); test(`${permission} key: Update ranking rules at null`, async () => { const client = await getClient(permission); - const task: EnqueuedTask = await client - .index(index.uid) - .updateRankingRules(null); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateRankingRules(null).waitTask(); - const response: string[] = await client - .index(index.uid) - .getRankingRules(); + const response = await client.index(index.uid).getRankingRules(); expect(response).toEqual(defaultRankingRules); }); test(`${permission} key: Reset ranking rules`, async () => { const client = await getClient(permission); - const task: EnqueuedTask = await client - .index(index.uid) - .resetRankingRules(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetRankingRules().waitTask(); - const response: string[] = await client - .index(index.uid) - .getRankingRules(); + const response = await client.index(index.uid).getRankingRules(); expect(response).toEqual(defaultRankingRules); }); diff --git a/tests/raw_document.test.ts b/tests/raw_document.test.ts index 96c80286a..be1b8aaf5 100644 --- a/tests/raw_document.test.ts +++ b/tests/raw_document.test.ts @@ -1,14 +1,12 @@ -import { expect, test, describe, beforeEach } from "vitest"; +import { expect, test, describe, beforeEach, assert } from "vitest"; import { clearAllIndexes, config, getClient, } from "./utils/meilisearch-test-utils.js"; -import { TaskStatus, ContentTypeEnum } from "../src/types.js"; +import { ContentTypeEnum } from "../src/types/index.js"; -beforeEach(async () => { - await clearAllIndexes(config); -}); +beforeEach(() => clearAllIndexes(config)); describe.each([{ permission: "Master" }, { permission: "Admin" }])( "Test on raw documents addition using `addDocumentsFromString`", @@ -19,13 +17,13 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( 123,Pride and Prejudice, A great book 546,Le Petit Prince,a french book`; - const { taskUid } = await client + const task = await client .index("csv_index") - .addDocumentsFromString(data, ContentTypeEnum.CSV); - const task = await client.waitForTask(taskUid); + .addDocumentsFromString(data, ContentTypeEnum.CSV) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Add documents in CSV format with custom primary key`, async () => { @@ -34,15 +32,15 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( 123,Pride and Prejudice, A great book 546,Le Petit Prince,a french book`; - const { taskUid } = await client + const task = await client .index("csv_index") .addDocumentsFromString(data, ContentTypeEnum.CSV, { primaryKey: "name", - }); - const task = await client.waitForTask(taskUid); + }) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Add documents in CSV format with custom delimiter`, async () => { @@ -51,16 +49,16 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( 123;Pride and Prejudice; A great book 546;Le Petit Prince;a french book`; - const { taskUid } = await client + const task = await client .index("csv_index") .addDocumentsFromString(data, ContentTypeEnum.CSV, { primaryKey: "name", csvDelimiter: ";", - }); - const task = await client.waitForTask(taskUid); + }) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Add documents in JSON lines format`, async () => { @@ -68,13 +66,13 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const data = `{ "id": 123, "title": "Pride and Prejudice", "comment": "A great book" } { "id": 456, "title": "Le Petit Prince", "comment": "A french book" }`; - const { taskUid } = await client + const task = await client .index("jsonl_index") - .addDocumentsFromString(data, ContentTypeEnum.NDJSON, {}); - const task = await client.waitForTask(taskUid); + .addDocumentsFromString(data, ContentTypeEnum.NDJSON, {}) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Add documents in JSON lines with custom primary key`, async () => { @@ -82,15 +80,15 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const data = `{ "name": 123, "title": "Pride and Prejudice", "comment": "A great book" } { "name": 456, "title": "Le Petit Prince", "comment": "A french book" }`; - const { taskUid } = await client + const task = await client .index("jsonl_index") .addDocumentsFromString(data, ContentTypeEnum.NDJSON, { primaryKey: "name", - }); - const task = await client.waitForTask(taskUid); + }) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Add documents in JSON format`, async () => { @@ -98,13 +96,13 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const data = `[{ "id": 123, "title": "Pride and Prejudice", "comment": "A great book" }, { "id": 456, "title": "Le Petit Prince", "comment": "A french book" }]`; - const { taskUid } = await client + const task = await client .index("json_index") - .addDocumentsFromString(data, ContentTypeEnum.JSON); - const task = await client.waitForTask(taskUid); + .addDocumentsFromString(data, ContentTypeEnum.JSON) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Add documents in JSON format with custom primary key`, async () => { @@ -112,15 +110,15 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const data = `[{ "name": 123, "title": "Pride and Prejudice", "comment": "A great book" }, { "name": 456, "title": "Le Petit Prince", "comment": "A french book" }]`; - const { taskUid } = await client + const task = await client .index("json_index") .addDocumentsFromString(data, ContentTypeEnum.JSON, { primaryKey: "name", - }); - const task = await client.waitForTask(taskUid); + }) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); }, ); @@ -134,13 +132,13 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( 123,Pride and Prejudice, A great book 546,Le Petit Prince,a french book`; - const { taskUid } = await client + const task = await client .index("csv_index") - .updateDocumentsFromString(data, ContentTypeEnum.CSV); - const task = await client.waitForTask(taskUid); + .updateDocumentsFromString(data, ContentTypeEnum.CSV) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Update documents in CSV format with custom primary key`, async () => { @@ -149,15 +147,15 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( 123,Pride and Prejudice, A great book 546,Le Petit Prince,a french book`; - const { taskUid } = await client + const task = await client .index("csv_index") .updateDocumentsFromString(data, ContentTypeEnum.CSV, { primaryKey: "name", - }); - const task = await client.waitForTask(taskUid); + }) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Update documents in CSV format with custom delimiter`, async () => { @@ -166,16 +164,16 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( 123;Pride and Prejudice; A great book 546;Le Petit Prince;a french book`; - const { taskUid } = await client + const task = await client .index("csv_index") .updateDocumentsFromString(data, ContentTypeEnum.CSV, { primaryKey: "name", csvDelimiter: ";", - }); - const task = await client.waitForTask(taskUid); + }) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Update documents in JSON lines format`, async () => { @@ -183,13 +181,13 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const data = `{ "id": 123, "title": "Pride and Prejudice", "comment": "A great book" } { "id": 456, "title": "Le Petit Prince", "comment": "A french book" }`; - const { taskUid } = await client + const task = await client .index("jsonl_index") - .updateDocumentsFromString(data, ContentTypeEnum.NDJSON); - const task = await client.waitForTask(taskUid); + .updateDocumentsFromString(data, ContentTypeEnum.NDJSON) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Update documents in JSON lines with custom primary key`, async () => { @@ -197,15 +195,15 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const data = `{ "name": 123, "title": "Pride and Prejudice", "comment": "A great book" } { "name": 456, "title": "Le Petit Prince", "comment": "A french book" }`; - const { taskUid } = await client + const task = await client .index("jsonl_index") .updateDocumentsFromString(data, ContentTypeEnum.NDJSON, { primaryKey: "name", - }); - const task = await client.waitForTask(taskUid); + }) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Update documents in JSON format`, async () => { @@ -213,13 +211,13 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const data = `[{ "id": 123, "title": "Pride and Prejudice", "comment": "A great book" }, { "id": 456, "title": "Le Petit Prince", "comment": "A french book" }]`; - const { taskUid } = await client + const task = await client .index("json_index") - .updateDocumentsFromString(data, ContentTypeEnum.JSON, {}); - const task = await client.waitForTask(taskUid); + .updateDocumentsFromString(data, ContentTypeEnum.JSON, {}) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); test(`${permission} key: Update documents in JSON format with custom primary key`, async () => { @@ -227,15 +225,15 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const data = `[{ "name": 123, "title": "Pride and Prejudice", "comment": "A great book" }, { "name": 456, "title": "Le Petit Prince", "comment": "A french book" }]`; - const { taskUid } = await client + const task = await client .index("json_index") .updateDocumentsFromString(data, ContentTypeEnum.JSON, { primaryKey: "name", - }); - const task = await client.waitForTask(taskUid); + }) + .waitTask(); - expect(task.details.receivedDocuments).toBe(2); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.details?.receivedDocuments).toBe(2); + assert.strictEqual(task.status, "succeeded"); }); }, ); diff --git a/tests/search.test.ts b/tests/search.test.ts index 9fb0e7512..76611c04a 100644 --- a/tests/search.test.ts +++ b/tests/search.test.ts @@ -7,12 +7,11 @@ import { beforeAll, vi, } from "vitest"; -import { ErrorStatusCode, MatchingStrategies } from "../src/types.js"; +import { ErrorStatusCode, MatchingStrategies } from "../src/types/index.js"; import type { FederatedMultiSearchParams, MultiSearchParams, -} from "../src/types.js"; -import { EnqueuedTask } from "../src/enqueued-task.js"; +} from "../src/types/index.js"; import { clearAllIndexes, config, @@ -131,18 +130,15 @@ describe.each([ await client.createIndex(emptyIndex.uid); const newFilterableAttributes = ["genre", "title", "id", "author"]; - const { taskUid: task1 }: EnqueuedTask = await client + await client .index(index.uid) .updateSettings({ filterableAttributes: newFilterableAttributes, sortableAttributes: ["id"], - }); - await client.waitForTask(task1); + }) + .waitTask(); - const { taskUid: task2 } = await client - .index(index.uid) - .addDocuments(dataset); - await client.waitForTask(task2); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Multi index search no queries`, async () => { @@ -298,17 +294,14 @@ describe.each([ // Setup to have a new "movies" index await masterClient.createIndex("movies"); const newFilterableAttributes = ["title", "id"]; - const { taskUid: task1 }: EnqueuedTask = await masterClient + await masterClient .index("movies") .updateSettings({ filterableAttributes: newFilterableAttributes, sortableAttributes: ["id"], - }); - await masterClient.waitForTask(task1); - const { taskUid: task2 } = await masterClient - .index("movies") - .addDocuments(movies); - await masterClient.waitForTask(task2); + }) + .waitTask(); + await masterClient.index("movies").addDocuments(movies).waitTask(); // Make a multi search on both indexes with facetsByIndex const response = await client.multiSearch< @@ -379,17 +372,14 @@ describe.each([ // Setup to have a new "movies" index await masterClient.createIndex("movies"); const newFilterableAttributes = ["title", "id"]; - const { taskUid: task1 }: EnqueuedTask = await masterClient + await masterClient .index("movies") .updateSettings({ filterableAttributes: newFilterableAttributes, sortableAttributes: ["id"], - }); - await masterClient.waitForTask(task1); - const { taskUid: task2 } = await masterClient - .index("movies") - .addDocuments(movies); - await masterClient.waitForTask(task2); + }) + .waitTask(); + await masterClient.index("movies").addDocuments(movies).waitTask(); // Make a multi search on both indexes with mergeFacets const response = await client.multiSearch< @@ -1229,12 +1219,12 @@ describe.each([ const client = await getClient(permission); const masterClient = await getClient("Master"); - const { taskUid } = await masterClient + await masterClient .index(index.uid) .updateLocalizedAttributes([ { attributePatterns: ["title", "comment"], locales: ["fra", "eng"] }, - ]); - await masterClient.waitForTask(taskUid); + ]) + .waitTask(); const searchResponse = await client.index(index.uid).search("french", { locales: ["fra", "eng"], @@ -1257,8 +1247,7 @@ describe.each([ test(`${permission} key: Try to search on deleted index and fail`, async () => { const client = await getClient(permission); const masterClient = await getClient("Master"); - const { taskUid } = await masterClient.index(index.uid).delete(); - await masterClient.waitForTask(taskUid); + await masterClient.index(index.uid).delete().waitTask(); await expect( client.index(index.uid).search("prince", {}), @@ -1271,8 +1260,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: Try Basic search and be denied`, async () => { @@ -1303,10 +1291,7 @@ describe.each([{ permission: "Master" }])( const client = await getClient("Master"); await client.createIndex(index.uid); - const { taskUid: documentAdditionTask } = await client - .index(index.uid) - .addDocuments(datasetWithNests); - await client.waitForTask(documentAdditionTask); + await client.index(index.uid).addDocuments(datasetWithNests).waitTask(); }); test(`${permission} key: search on nested content with no parameters`, async () => { @@ -1325,12 +1310,12 @@ describe.each([{ permission: "Master" }])( test(`${permission} key: search on nested content with searchable on specific nested field`, async () => { const client = await getClient(permission); - const { taskUid: settingsUpdateTask }: EnqueuedTask = await client + await client .index(index.uid) .updateSettings({ searchableAttributes: ["title", "info.comment"], - }); - await client.waitForTask(settingsUpdateTask); + }) + .waitTask(); const response = await client.index(index.uid).search("An awesome", {}); @@ -1346,13 +1331,13 @@ describe.each([{ permission: "Master" }])( test(`${permission} key: search on nested content with sort`, async () => { const client = await getClient(permission); - const { taskUid: settingsUpdateTask }: EnqueuedTask = await client + await client .index(index.uid) .updateSettings({ searchableAttributes: ["title", "info.comment"], sortableAttributes: ["info.reviewNb"], - }); - await client.waitForTask(settingsUpdateTask); + }) + .waitTask(); const response = await client.index(index.uid).search("", { sort: ["info.reviewNb:desc"], @@ -1378,8 +1363,7 @@ describe.each([ beforeAll(async () => { const client = await getClient("Master"); await clearAllIndexes(config); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: search on index and abort`, async () => { diff --git a/tests/search_cutoff_ms.test.ts b/tests/search_cutoff_ms.test.ts index 7f8d6f477..7c96faa04 100644 --- a/tests/search_cutoff_ms.test.ts +++ b/tests/search_cutoff_ms.test.ts @@ -6,7 +6,7 @@ import { expect, test, } from "vitest"; -import { ErrorStatusCode, type SearchCutoffMs } from "../src/types.js"; +import { ErrorStatusCode, type SearchCutoffMs } from "../src/index.js"; import { clearAllIndexes, config, @@ -32,8 +32,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default searchCutoffMs settings`, async () => { @@ -46,10 +45,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update searchCutoffMs to valid value`, async () => { const client = await getClient(permission); const newSearchCutoffMs = 100; - const task = await client + await client .index(index.uid) - .updateSearchCutoffMs(newSearchCutoffMs); - await client.waitForTask(task.taskUid); + .updateSearchCutoffMs(newSearchCutoffMs) + .waitTask(); const response = await client.index(index.uid).getSearchCutoffMs(); @@ -59,10 +58,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update searchCutoffMs to null`, async () => { const client = await getClient(permission); const newSearchCutoffMs = null; - const task = await client + await client .index(index.uid) - .updateSearchCutoffMs(newSearchCutoffMs); - await client.index(index.uid).waitForTask(task.taskUid); + .updateSearchCutoffMs(newSearchCutoffMs) + .waitTask(); const response = await client.index(index.uid).getSearchCutoffMs(); @@ -84,12 +83,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Reset searchCutoffMs`, async () => { const client = await getClient(permission); const newSearchCutoffMs = 100; - const updateTask = await client + await client .index(index.uid) - .updateSearchCutoffMs(newSearchCutoffMs); - await client.waitForTask(updateTask.taskUid); - const task = await client.index(index.uid).resetSearchCutoffMs(); - await client.waitForTask(task.taskUid); + .updateSearchCutoffMs(newSearchCutoffMs) + .waitTask(); + await client.index(index.uid).resetSearchCutoffMs().waitTask(); const response = await client.index(index.uid).getSearchCutoffMs(); @@ -103,8 +101,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get searchCutoffMs and be denied`, async () => { @@ -135,8 +132,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get searchCutoffMs and be denied`, async () => { diff --git a/tests/searchable_attributes.test.ts b/tests/searchable_attributes.test.ts index f250e0a8d..8a1b1030f 100644 --- a/tests/searchable_attributes.test.ts +++ b/tests/searchable_attributes.test.ts @@ -6,7 +6,7 @@ import { expect, test, } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -29,16 +29,13 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default searchable attributes`, async () => { const client = await getClient(permission); - const response: string[] = await client - .index(index.uid) - .getSearchableAttributes(); + const response = await client.index(index.uid).getSearchableAttributes(); expect(response).toEqual(["*"]); }); @@ -46,40 +43,30 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update searchable attributes`, async () => { const client = await getClient(permission); const newSearchableAttributes = ["title"]; - const task = await client + await client .index(index.uid) - .updateSearchableAttributes(newSearchableAttributes); - await client.index(index.uid).waitForTask(task.taskUid); + .updateSearchableAttributes(newSearchableAttributes) + .waitTask(); - const response: string[] = await client - .index(index.uid) - .getSearchableAttributes(); + const response = await client.index(index.uid).getSearchableAttributes(); expect(response).toEqual(newSearchableAttributes); }); test(`${permission} key: Update searchable attributes at null`, async () => { const client = await getClient(permission); - const task = await client - .index(index.uid) - .updateSearchableAttributes(null); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateSearchableAttributes(null).waitTask(); - const response: string[] = await client - .index(index.uid) - .getSearchableAttributes(); + const response = await client.index(index.uid).getSearchableAttributes(); expect(response).toEqual(["*"]); }); test(`${permission} key: Reset searchable attributes`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).resetSearchableAttributes(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetSearchableAttributes().waitTask(); - const response: string[] = await client - .index(index.uid) - .getSearchableAttributes(); + const response = await client.index(index.uid).getSearchableAttributes(); expect(response).toEqual(["*"]); }); @@ -91,8 +78,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get searchable attributes and be denied`, async () => { @@ -123,8 +109,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get searchable attributes and be denied`, async () => { diff --git a/tests/separator_tokens.test.ts b/tests/separator_tokens.test.ts index 6b5379f8c..d780eacde 100644 --- a/tests/separator_tokens.test.ts +++ b/tests/separator_tokens.test.ts @@ -1,5 +1,4 @@ import { afterAll, beforeEach, describe, expect, test } from "vitest"; -import { EnqueuedTask } from "../src/enqueued-task.js"; import { clearAllIndexes, config, @@ -22,15 +21,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default separator tokens`, async () => { const client = await getClient(permission); - const response: string[] = await client - .index(index.uid) - .getSeparatorTokens(); + const response = await client.index(index.uid).getSeparatorTokens(); expect(response).toEqual([]); }); @@ -38,14 +34,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update separator tokens`, async () => { const client = await getClient(permission); const newSeparatorTokens = ["&sep", "/", "|"]; - const task: EnqueuedTask = await client + await client .index(index.uid) - .updateSeparatorTokens(newSeparatorTokens); - await client.index(index.uid).waitForTask(task.taskUid); + .updateSeparatorTokens(newSeparatorTokens) + .waitTask(); - const response: string[] = await client - .index(index.uid) - .getSeparatorTokens(); + const response = await client.index(index.uid).getSeparatorTokens(); expect(response).toEqual(newSeparatorTokens); }); @@ -53,28 +47,21 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update separator tokens with null value`, async () => { const client = await getClient(permission); const newSeparatorTokens = null; - const task: EnqueuedTask = await client + await client .index(index.uid) - .updateSeparatorTokens(newSeparatorTokens); - await client.index(index.uid).waitForTask(task.taskUid); + .updateSeparatorTokens(newSeparatorTokens) + .waitTask(); - const response: string[] = await client - .index(index.uid) - .getSeparatorTokens(); + const response = await client.index(index.uid).getSeparatorTokens(); expect(response).toEqual([]); }); test(`${permission} key: Reset separator tokens`, async () => { const client = await getClient(permission); - const task: EnqueuedTask = await client - .index(index.uid) - .resetSeparatorTokens(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetSeparatorTokens().waitTask(); - const response: string[] = await client - .index(index.uid) - .getSeparatorTokens(); + const response = await client.index(index.uid).getSeparatorTokens(); expect(response).toEqual([]); }); diff --git a/tests/settings.test.ts b/tests/settings.test.ts index 2296f4ced..c6c71dd75 100644 --- a/tests/settings.test.ts +++ b/tests/settings.test.ts @@ -1,5 +1,5 @@ import { afterAll, beforeEach, describe, expect, test } from "vitest"; -import { ErrorStatusCode, type Settings } from "../src/types.js"; +import { ErrorStatusCode, type Settings } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -27,17 +27,14 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - const { taskUid: AddDocPkTask } = await client + await client .index(indexAndPK.uid) .addDocuments(dataset, { primaryKey: indexAndPK.primaryKey, - }); - await client.waitForTask(AddDocPkTask); + }) + .waitTask(); - const { taskUid: AddDocTask } = await client - .index(index.uid) - .addDocuments(dataset, {}); - await client.waitForTask(AddDocTask); + await client.index(index.uid).addDocuments(dataset, {}).waitTask(); }); test(`${permission} key: Get default settings of an index`, async () => { @@ -94,8 +91,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( prefixSearch: "indexingTime", }; // Add the settings - const task = await client.index(index.uid).updateSettings(newSettings); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateSettings(newSettings).waitTask(); // Fetch the settings const response = await client.index(index.uid).getSettings(); @@ -137,8 +133,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( searchCutoffMs: null, }; // Add the settings - const task = await client.index(index.uid).updateSettings(newSettings); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateSettings(newSettings).waitTask(); // Fetch the settings const response = await client.index(index.uid).getSettings(); @@ -159,10 +154,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( }, }, }; - const task = await client.index(index.uid).updateSettings(newSettings); await client .index(index.uid) - .waitForTask(task.taskUid, { timeOutMs: 60_000 }); + .updateSettings(newSettings) + .waitTask({ timeout: 60_000 }); const response = await client.index(index.uid).getSettings(); expect(response).toMatchSnapshot(); @@ -175,10 +170,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( rankingRules: ["title:asc", "typo"], stopWords: ["the"], }; - const task = await client - .index(indexAndPK.uid) - .updateSettings(newSettings); - await client.index(indexAndPK.uid).waitForTask(task.taskUid); + await client.index(indexAndPK.uid).updateSettings(newSettings).waitTask(); const response = await client.index(indexAndPK.uid).getSettings(); @@ -187,8 +179,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Reset settings`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).resetSettings(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetSettings().waitTask(); const response = await client.index(index.uid).getSettings(); @@ -197,8 +188,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Reset settings of empty index`, async () => { const client = await getClient(permission); - const task = await client.index(indexAndPK.uid).resetSettings(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(indexAndPK.uid).resetSettings().waitTask(); const response = await client.index(indexAndPK.uid).getSettings(); @@ -211,8 +201,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const newSettings: Settings = { embedders: null, }; - const task = await client.index(index.uid).updateSettings(newSettings); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateSettings(newSettings).waitTask(); const response = await client.index(index.uid).getSettings(); expect(response).toMatchSnapshot(); @@ -223,8 +212,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const newSettings = { searchableAttributes: ["title"], }; - const task = await client.index(index.uid).updateSettings(newSettings); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateSettings(newSettings).waitTask(); const response = await client.index(index.uid).getSettings(); @@ -237,11 +225,8 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( searchableAttributes: ["title"], }; // Update settings - const task = await client - .index(indexAndPK.uid) - .updateSettings(newSettings); + await client.index(indexAndPK.uid).updateSettings(newSettings).waitTask(); // Wait for setting addition to be done - await client.index(index.uid).waitForTask(task.taskUid); // Fetch settings const response = await client.index(indexAndPK.uid).getSettings(); @@ -252,10 +237,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update facetSearch settings on empty index`, async () => { const client = await getClient(permission); - const { taskUid } = await client + await client .index(index.uid) - .updateSettings({ facetSearch: false }); - await client.index(index.uid).waitForTask(taskUid); + .updateSettings({ facetSearch: false }) + .waitTask(); const response = await client.index(index.uid).getSettings(); expect(response).toMatchSnapshot(); @@ -264,10 +249,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update prefixSearch settings on an empty index`, async () => { const client = await getClient(permission); - const { taskUid } = await client + await client .index(index.uid) - .updateSettings({ prefixSearch: "disabled" }); - await client.index(index.uid).waitForTask(taskUid); + .updateSettings({ prefixSearch: "disabled" }) + .waitTask(); const response = await client.index(index.uid).getSettings(); expect(response).toMatchSnapshot(); diff --git a/tests/snapshots.test.ts b/tests/snapshots.test.ts index be952d541..7b07ab897 100644 --- a/tests/snapshots.test.ts +++ b/tests/snapshots.test.ts @@ -1,5 +1,5 @@ -import { beforeEach, describe, expect, test } from "vitest"; -import { ErrorStatusCode, TaskStatus } from "../src/types.js"; +import { beforeEach, describe, expect, test, assert } from "vitest"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -17,11 +17,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { test(`${permission} key: create a new snapshot`, async () => { const client = await getClient(permission); - const { taskUid } = await client.createSnapshot(); + const taskResult = await client.createSnapshot().waitTask(); - const taskResult = await client.waitForTask(taskUid); - - expect(taskResult).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); + assert.strictEqual(taskResult.status, "succeeded"); }); }, ); diff --git a/tests/sortable_attributes.test.ts b/tests/sortable_attributes.test.ts index 90a306a9b..814c7f7f0 100644 --- a/tests/sortable_attributes.test.ts +++ b/tests/sortable_attributes.test.ts @@ -6,7 +6,7 @@ import { expect, test, } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -29,13 +29,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); - const { taskUid: docTask } = await client - .index(index.uid) - .addDocuments(dataset); - await client.waitForTask(docTask); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default sortable attributes`, async () => { @@ -49,10 +45,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update sortable attributes`, async () => { const client = await getClient(permission); const newSortableAttributes = ["title"]; - const task = await client + await client .index(index.uid) - .updateSortableAttributes(newSortableAttributes); - await client.index(index.uid).waitForTask(task.taskUid); + .updateSortableAttributes(newSortableAttributes) + .waitTask(); const response = await client.index(index.uid).getSortableAttributes(); expect(response).toEqual(newSortableAttributes); @@ -60,8 +56,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update sortable attributes at null`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).updateSortableAttributes(null); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateSortableAttributes(null).waitTask(); const response = await client.index(index.uid).getSortableAttributes(); @@ -70,8 +65,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Reset sortable attributes`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).resetSortableAttributes(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetSortableAttributes().waitTask(); const response = await client.index(index.uid).getSortableAttributes(); @@ -85,8 +79,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get sortable attributes and be denied`, async () => { @@ -117,8 +110,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: try to get sortable attributes and be denied`, async () => { diff --git a/tests/stop_words.test.ts b/tests/stop_words.test.ts index bbec0e38c..e56582c2c 100644 --- a/tests/stop_words.test.ts +++ b/tests/stop_words.test.ts @@ -1,6 +1,5 @@ import { afterAll, beforeEach, describe, expect, test } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; -import { EnqueuedTask } from "../src/enqueued-task.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -23,8 +22,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default stop words`, async () => { @@ -37,12 +35,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update stop words`, async () => { const client = await getClient(permission); const newStopWords = ["the"]; - const task: EnqueuedTask = await client - .index(index.uid) - .updateStopWords(newStopWords); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateStopWords(newStopWords).waitTask(); - const response: string[] = await client.index(index.uid).getStopWords(); + const response = await client.index(index.uid).getStopWords(); expect(response).toEqual(newStopWords); }); @@ -50,22 +45,18 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update stop words with null value`, async () => { const client = await getClient(permission); const newStopWords = null; - const task: EnqueuedTask = await client - .index(index.uid) - .updateStopWords(newStopWords); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateStopWords(newStopWords).waitTask(); - const response: string[] = await client.index(index.uid).getStopWords(); + const response = await client.index(index.uid).getStopWords(); expect(response).toEqual([]); }); test(`${permission} key: Reset stop words`, async () => { const client = await getClient(permission); - const task: EnqueuedTask = await client.index(index.uid).resetStopWords(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetStopWords().waitTask(); - const response: string[] = await client.index(index.uid).getStopWords(); + const response = await client.index(index.uid).getStopWords(); expect(response).toEqual([]); }); diff --git a/tests/synonyms.test.ts b/tests/synonyms.test.ts index d8ad653be..48a11835b 100644 --- a/tests/synonyms.test.ts +++ b/tests/synonyms.test.ts @@ -1,5 +1,5 @@ import { afterAll, beforeEach, describe, expect, test } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -22,8 +22,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default synonyms`, async () => { @@ -38,10 +37,9 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const newSynonyms = { hp: ["harry potter"], }; - const task = await client.index(index.uid).updateSynonyms(newSynonyms); - await client.waitForTask(task.taskUid); + await client.index(index.uid).updateSynonyms(newSynonyms).waitTask(); - const response: object = await client.index(index.uid).getSynonyms(); + const response = await client.index(index.uid).getSynonyms(); expect(response).toEqual(newSynonyms); }); @@ -49,20 +47,18 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update synonyms with null value`, async () => { const client = await getClient(permission); const newSynonyms = null; - const task = await client.index(index.uid).updateSynonyms(newSynonyms); - await client.waitForTask(task.taskUid); + await client.index(index.uid).updateSynonyms(newSynonyms).waitTask(); - const response: object = await client.index(index.uid).getSynonyms(); + const response = await client.index(index.uid).getSynonyms(); expect(response).toEqual({}); }); test(`${permission} key: Reset synonyms`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).resetSynonyms(); - await client.waitForTask(task.taskUid); + await client.index(index.uid).resetSynonyms().waitTask(); - const response: object = await client.index(index.uid).getSynonyms(); + const response = await client.index(index.uid).getSynonyms(); expect(response).toEqual({}); }); diff --git a/tests/task.test.ts b/tests/task.test.ts index 84f3a20d8..2032e9747 100644 --- a/tests/task.test.ts +++ b/tests/task.test.ts @@ -1,13 +1,13 @@ -import { afterAll, beforeEach, describe, expect, test } from "vitest"; -import { ErrorStatusCode, TaskTypes, TaskStatus } from "../src/types.js"; +import { afterAll, assert, beforeEach, describe, expect, test } from "vitest"; +import { ErrorStatusCode } from "../src/types/index.js"; import { sleep } from "../src/utils.js"; import { + BAD_HOST, clearAllIndexes, config, - BAD_HOST, - MeiliSearch, - getClient, dataset, + getClient, + MeiliSearch, } from "./utils/meilisearch-test-utils.js"; const index = { @@ -31,8 +31,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); test(`${permission} key: Get one enqueued task`, async () => { @@ -43,56 +42,45 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( expect(enqueuedTask.taskUid).toBeDefined(); expect(enqueuedTask.indexUid).toEqual(index.uid); expect(enqueuedTask.status).toBeDefined(); - expect(enqueuedTask.type).toEqual(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE); + assert.strictEqual(enqueuedTask.type, "documentAdditionOrUpdate"); expect(enqueuedTask.enqueuedAt).toBeDefined(); - expect(enqueuedTask.enqueuedAt).toBeInstanceOf(Date); + expect(enqueuedTask.enqueuedAt).toBeTypeOf("string"); }); test(`${permission} key: Get one task`, async () => { const client = await getClient(permission); const enqueuedTask = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(enqueuedTask.taskUid); + await client.tasks.waitForTask(enqueuedTask.taskUid); - const task = await client.getTask(enqueuedTask.taskUid); + const task = await client.tasks.getTask(enqueuedTask.taskUid); expect(task.indexUid).toEqual(index.uid); expect(task.batchUid).toBeDefined(); - expect(task.status).toEqual(TaskStatus.TASK_SUCCEEDED); - expect(task.type).toEqual(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE); + assert.strictEqual(task.status, "succeeded"); + assert.strictEqual(task.type, "documentAdditionOrUpdate"); expect(task.uid).toEqual(enqueuedTask.taskUid); expect(task).toHaveProperty("details"); - expect(task.details.indexedDocuments).toEqual(7); - expect(task.details.receivedDocuments).toEqual(7); + expect(task.details?.indexedDocuments).toEqual(7); + expect(task.details?.receivedDocuments).toEqual(7); expect(task.duration).toBeDefined(); expect(task.enqueuedAt).toBeDefined(); - expect(task.enqueuedAt).toBeInstanceOf(Date); + expect(task.enqueuedAt).toBeTypeOf("string"); expect(task.finishedAt).toBeDefined(); - expect(task.finishedAt).toBeInstanceOf(Date); + expect(task.finishedAt).toBeTypeOf("string"); expect(task.startedAt).toBeDefined(); - expect(task.startedAt).toBeInstanceOf(Date); + expect(task.startedAt).toBeTypeOf("string"); expect(task.error).toBeNull(); }); - test(`${permission} key: Get one task with index instance`, async () => { - const client = await getClient(permission); - const enqueuedTask = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(enqueuedTask.taskUid); - - const task = await client.index(index.uid).getTask(enqueuedTask.taskUid); - - expect(task.indexUid).toEqual(index.uid); - expect(task.uid).toEqual(enqueuedTask.taskUid); - }); - // get tasks test(`${permission} key: Get all tasks`, async () => { const client = await getClient(permission); const enqueuedTask = await client .index(index.uid) .addDocuments([{ id: 1 }]); - await client.waitForTask(enqueuedTask.taskUid); + await client.tasks.waitForTask(enqueuedTask.taskUid); - const tasks = await client.getTasks(); + const tasks = await client.tasks.getTasks(); expect(tasks.results).toBeInstanceOf(Array); expect(tasks.total).toBeDefined(); @@ -106,33 +94,8 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( await client.index(index.uid).deleteDocument(1); await client.createIndex(index2.uid); - const tasks = await client.getTasks({ - types: [ - TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE, - TaskTypes.DOCUMENT_DELETION, - ], - }); - const onlyDocumentAddition = new Set( - tasks.results.map((task) => task.type), - ); - - expect(onlyDocumentAddition.size).toEqual(2); - }); - - // get tasks: type - test(`${permission} key: Get all tasks with type filter on an index`, async () => { - const client = await getClient(permission); - await client.deleteIndex(index2.uid); - await client.createIndex(index2.uid); - await client.index(index.uid).addDocuments([{ id: 1 }]); - await client.index(index2.uid).addDocuments([{ id: 1 }]); - await client.index(index2.uid).deleteDocument(1); - - const tasks = await client.index(index.uid).getTasks({ - types: [ - TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE, - TaskTypes.DOCUMENT_DELETION, - ], + const tasks = await client.tasks.getTasks({ + types: ["documentAdditionOrUpdate", "documentDeletion"], }); const onlyDocumentAddition = new Set( tasks.results.map((task) => task.type), @@ -145,11 +108,16 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Get all tasks with pagination`, async () => { const client = await getClient(permission); const task1 = await client.index(index.uid).addDocuments([{ id: 1 }]); - const task2 = await client.index(index.uid).addDocuments([{ id: 1 }]); - await client.waitForTask(task1.taskUid); - await client.waitForTask(task2.taskUid); + await client + .index(index.uid) + .addDocuments([{ id: 1 }]) + .waitTask(); + await client.tasks.waitForTask(task1.taskUid); - const tasks = await client.getTasks({ from: task1.taskUid, limit: 1 }); + const tasks = await client.tasks.getTasks({ + from: task1.taskUid, + limit: 1, + }); expect(tasks.results.length).toEqual(1); expect(tasks.from).toEqual(task1.taskUid); @@ -160,13 +128,14 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( // get tasks: status test(`${permission} key: Get all tasks with status filter`, async () => { const client = await getClient(permission); - const task1 = await client.index(index.uid).addDocuments([{ id: 1 }]); - const task2 = await client.index(index.uid).addDocuments([{}]); - await client.waitForTask(task1.taskUid); - await client.waitForTask(task2.taskUid); + await client + .index(index.uid) + .addDocuments([{ id: 1 }]) + .waitTask(); + await client.index(index.uid).addDocuments([{}]).waitTask(); - const tasks = await client.getTasks({ - statuses: [TaskStatus.TASK_SUCCEEDED, TaskStatus.TASK_FAILED], + const tasks = await client.tasks.getTasks({ + statuses: ["succeeded", "failed"], }); const onlySuccesfullTasks = new Set( tasks.results.map((task) => task.status), @@ -175,30 +144,6 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( expect(onlySuccesfullTasks.size).toEqual(2); }); - // get tasks: status - test(`${permission} key: Get all tasks with status filter on an index`, async () => { - const client = await getClient(permission); - const task1 = await client.index(index.uid).addDocuments([{ id: 1 }]); - const task2 = await client.index(index.uid).addDocuments([{}]); - const task3 = await client.index(index2.uid).addDocuments([{}]); - await client.waitForTask(task1.taskUid); - await client.waitForTask(task2.taskUid); - await client.waitForTask(task3.taskUid); - - const tasks = await client.index(index.uid).getTasks({ - statuses: [TaskStatus.TASK_SUCCEEDED, TaskStatus.TASK_FAILED], - }); - const onlySuccesfullTasks = new Set( - tasks.results.map((task) => task.status), - ); - const onlyTaskWithSameUid = new Set( - tasks.results.map((task) => task.indexUid), - ); - - expect(onlySuccesfullTasks.size).toEqual(2); - expect(onlyTaskWithSameUid.size).toEqual(1); - }); - // get tasks: indexUid test(`${permission} key: Get all tasks with indexUid filter`, async () => { const client = await getClient(permission); @@ -206,7 +151,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( await client.index(index2.uid).addDocuments([{ id: 1 }]); await client.index(index3.uid).addDocuments([{ id: 1 }]); - const tasks = await client.getTasks({ + const tasks = await client.tasks.getTasks({ indexUids: [index.uid, index2.uid], }); const onlyTaskWithSameUid = new Set( @@ -223,7 +168,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( .index(index.uid) .addDocuments([{ id: 1 }]); - const tasks = await client.getTasks({ + const tasks = await client.tasks.getTasks({ uids: [taskUid], }); @@ -241,8 +186,8 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( .index(index.uid) .addDocuments([{ id: 1 }]); - const tasks = await client.getTasks({ - beforeEnqueuedAt: currentTime, + const tasks = await client.tasks.getTasks({ + beforeEnqueuedAt: currentTime.toISOString(), }); const tasksUids = tasks.results.map((t) => t.uid); @@ -260,8 +205,8 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const tasks = await client.getTasks({ - afterEnqueuedAt: currentTime, + const tasks = await client.tasks.getTasks({ + afterEnqueuedAt: currentTime.toISOString(), }); const tasksUids = tasks.results.map((t) => t.uid); @@ -278,10 +223,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const { taskUid } = await client .index(index.uid) .addDocuments([{ id: 1 }]); - await client.index(index.uid).waitForTask(taskUid); // ensures the tasks has a `startedAt` value + await client.tasks.waitForTask(taskUid); // ensures the tasks has a `startedAt` value - const tasks = await client.getTasks({ - beforeStartedAt: currentTime, + const tasks = await client.tasks.getTasks({ + beforeStartedAt: currentTime.toISOString(), }); const tasksUids = tasks.results.map((t) => t.uid); @@ -294,14 +239,14 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const { taskUid } = await client .index(index.uid) .addDocuments([{ id: 1 }]); - await client.index(index.uid).waitForTask(taskUid); // ensures the tasks has a `startedAt` value + await client.tasks.waitForTask(taskUid); // ensures the tasks has a `startedAt` value await sleep(1); // in ms const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const tasks = await client.getTasks({ - afterStartedAt: currentTime, + const tasks = await client.tasks.getTasks({ + afterStartedAt: currentTime.toISOString(), }); const tasksUids = tasks.results.map((t) => t.uid); @@ -318,10 +263,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const { taskUid } = await client .index(index.uid) .addDocuments([{ id: 1 }]); - await client.index(index.uid).waitForTask(taskUid); // ensures the tasks has a `finishedAt` value + await client.tasks.waitForTask(taskUid); // ensures the tasks has a `finishedAt` value - const tasks = await client.getTasks({ - beforeFinishedAt: currentTime, + const tasks = await client.tasks.getTasks({ + beforeFinishedAt: currentTime.toISOString(), }); const tasksUids = tasks.results.map((t) => t.uid); @@ -334,14 +279,14 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const { taskUid } = await client .index(index.uid) .addDocuments([{ id: 1 }]); - await client.index(index.uid).waitForTask(taskUid); // ensures the tasks has a `finishedAt` value + await client.tasks.waitForTask(taskUid); // ensures the tasks has a `finishedAt` value await sleep(1); // in ms const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const tasks = await client.getTasks({ - afterFinishedAt: currentTime, + const tasks = await client.tasks.getTasks({ + afterFinishedAt: currentTime.toISOString(), }); const tasksUids = tasks.results.map((t) => t.uid); @@ -356,16 +301,12 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( .addDocuments([{ id: 1 }]); // Cancel the task - const enqueuedCancelationTask = await client.cancelTasks({ - uids: [addDocumentsTask.taskUid], - }); - // wait for the task to be fully canceled - const cancelationTask = await client.waitForTask( - enqueuedCancelationTask.taskUid, - ); + const cancelationTask = await client.tasks + .cancelTasks({ uids: [addDocumentsTask.taskUid] }) + .waitTask(); - expect(cancelationTask.type).toEqual(TaskTypes.TASK_CANCELATION); - expect(cancelationTask.details.originalFilter).toEqual( + assert.strictEqual(cancelationTask.type, "taskCancelation"); + expect(cancelationTask.details?.originalFilter).toEqual( `?uids=${addDocumentsTask.taskUid}`, ); }); @@ -378,12 +319,14 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const taskA = await client.index(index.uid).addDocuments([{ id: 1 }]); const taskB = await client.index(index.uid).addDocuments([{ id: 2 }]); - await client.waitForTask(taskA.taskUid); - await client.waitForTask(taskB.taskUid); + await client.tasks.waitForTask(taskA.taskUid); + await client.tasks.waitForTask(taskB.taskUid); - const tasks = await client.getTasks({ afterEnqueuedAt: currentTime }); - const reversedTasks = await client.getTasks({ - afterEnqueuedAt: currentTime, + const tasks = await client.tasks.getTasks({ + afterEnqueuedAt: currentTime.toISOString(), + }); + const reversedTasks = await client.tasks.getTasks({ + afterEnqueuedAt: currentTime.toISOString(), reverse: true, }); expect(tasks.results.map((t) => t.uid)).toEqual([ @@ -401,8 +344,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const client = await getClient(permission); await expect( - // @ts-expect-error testing wrong argument type - client.getTasks({ types: ["wrong"] }), + client.tasks.getTasks( + // @ts-expect-error testing wrong argument type + { types: ["wrong"] }, + ), ).rejects.toHaveProperty( "cause.code", ErrorStatusCode.INVALID_TASK_TYPES, @@ -414,8 +359,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const client = await getClient(permission); await expect( - // @ts-expect-error testing wrong argument type - client.getTasks({ statuses: ["wrong"] }), + client.tasks.getTasks( + // @ts-expect-error testing wrong argument type + { statuses: ["wrong"] }, + ), ).rejects.toHaveProperty( "cause.code", ErrorStatusCode.INVALID_TASK_STATUSES, @@ -427,8 +374,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const client = await getClient(permission); await expect( - // @ts-expect-error testing wrong argument type - client.getTasks({ uids: ["wrong"] }), + client.tasks.getTasks( + // @ts-expect-error testing wrong argument type + { uids: ["wrong"] }, + ), ).rejects.toHaveProperty("cause.code", ErrorStatusCode.INVALID_TASK_UIDS); }); @@ -437,8 +386,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const client = await getClient(permission); await expect( - // @ts-expect-error testing wrong canceledBy type - client.getTasks({ canceledBy: ["wrong"] }), + client.tasks.getTasks( + // @ts-expect-error testing wrong canceledBy type + { canceledBy: ["wrong"] }, + ), ).rejects.toHaveProperty( "cause.code", ErrorStatusCode.INVALID_TASK_CANCELED_BY, @@ -450,8 +401,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const client = await getClient(permission); await expect( - // @ts-expect-error testing wrong date format - client.getTasks({ beforeEnqueuedAt: "wrong" }), + client.tasks.getTasks({ beforeEnqueuedAt: "wrong" }), ).rejects.toHaveProperty( "cause.code", ErrorStatusCode.INVALID_TASK_BEFORE_ENQUEUED_AT, @@ -465,12 +415,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( .index(index.uid) .addDocuments([{ id: 1 }]); - const enqueuedTask = await client.cancelTasks({ - uids: [addDocuments.taskUid], - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .cancelTasks({ uids: [addDocuments.taskUid] }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + assert.strictEqual(task.type, "taskCancelation"); expect(task.details?.originalFilter).toContain("uids="); expect(task.details?.matchedTasks).toBeDefined(); expect(task.details?.canceledTasks).toBeDefined(); @@ -480,12 +429,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Cancel a task using the indexUid filter`, async () => { const client = await getClient(permission); - const enqueuedTask = await client.cancelTasks({ - indexUids: [index.uid], - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .cancelTasks({ indexUids: [index.uid] }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + assert.strictEqual(task.type, "taskCancelation"); expect(task.details?.originalFilter).toEqual("?indexUids=movies_test"); }); @@ -493,15 +441,13 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Cancel a task using the type filter`, async () => { const client = await getClient(permission); - const enqueuedTask = await client.cancelTasks({ - types: [ - TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE, - TaskTypes.DOCUMENT_DELETION, - ], - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .cancelTasks({ + types: ["documentAdditionOrUpdate", "documentDeletion"], + }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + assert.strictEqual(task.type, "taskCancelation"); expect(task.details?.originalFilter).toEqual( "?types=documentAdditionOrUpdate%2CdocumentDeletion", ); @@ -511,12 +457,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Cancel a task using the status filter`, async () => { const client = await getClient(permission); - const enqueuedTask = await client.cancelTasks({ - statuses: [TaskStatus.TASK_ENQUEUED, TaskStatus.TASK_PROCESSING], - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .cancelTasks({ statuses: ["enqueued", "processing"] }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + assert.strictEqual(task.type, "taskCancelation"); expect(task.details?.originalFilter).toEqual( "?statuses=enqueued%2Cprocessing", ); @@ -528,12 +473,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.cancelTasks({ - beforeEnqueuedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .cancelTasks({ beforeEnqueuedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + assert.strictEqual(task.type, "taskCancelation"); expect(task.details?.originalFilter).toContain("beforeEnqueuedAt"); }); @@ -543,12 +487,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.cancelTasks({ - afterEnqueuedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .cancelTasks({ afterEnqueuedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + assert.strictEqual(task.type, "taskCancelation"); expect(task.details?.originalFilter).toContain("afterEnqueuedAt"); }); @@ -558,12 +501,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.cancelTasks({ - beforeStartedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .cancelTasks({ beforeStartedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + assert.strictEqual(task.type, "taskCancelation"); expect(task.details?.originalFilter).toContain("beforeStartedAt"); }); @@ -573,12 +515,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.cancelTasks({ - afterStartedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .cancelTasks({ afterStartedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + assert.strictEqual(task.type, "taskCancelation"); expect(task.details?.originalFilter).toContain("afterStartedAt"); }); @@ -588,27 +529,25 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.cancelTasks({ - beforeFinishedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .cancelTasks({ beforeFinishedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + assert.strictEqual(task.type, "taskCancelation"); expect(task.details?.originalFilter).toContain("beforeFinishedAt"); }); // cancel: afterFinishedAt - test(`${permission} key: Cancel a task using afterFinishedAt filter`, async () => { + test(`${permission} key: Cancel a task using afterFinishedAt filter with no timeout`, async () => { const client = await getClient(permission); const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.cancelTasks({ - afterFinishedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .cancelTasks({ afterFinishedAt: currentTime.toISOString() }) + .waitTask({ timeout: 0 }); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + assert.strictEqual(task.type, "taskCancelation"); expect(task.details?.originalFilter).toContain("afterFinishedAt"); }); @@ -616,7 +555,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Try to cancel without filters and fail`, async () => { const client = await getClient(permission); - await expect(client.cancelTasks()).rejects.toHaveProperty( + await expect(client.tasks.cancelTasks({})).rejects.toHaveProperty( "cause.code", ErrorStatusCode.MISSING_TASK_FILTERS, ); @@ -629,17 +568,15 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( .index(index.uid) .addDocuments([{ id: 1 }]); - const deleteTask = await client.deleteTasks({ - uids: [addDocuments.taskUid], - }); - const task = await client.waitForTask(deleteTask.taskUid); + const task = await client.tasks + .deleteTasks({ uids: [addDocuments.taskUid] }) + .waitTask(); - expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION); + assert.strictEqual(task.type, "taskDeletion"); expect(task.details?.deletedTasks).toBeDefined(); - await expect(client.getTask(addDocuments.taskUid)).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.TASK_NOT_FOUND, - ); + await expect( + client.tasks.getTask(addDocuments.taskUid), + ).rejects.toHaveProperty("cause.code", ErrorStatusCode.TASK_NOT_FOUND); }); // delete: indexUid @@ -649,31 +586,27 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( .index(index.uid) .addDocuments([{ id: 1 }]); - const enqueuedTask = await client.deleteTasks({ - indexUids: [index.uid], - }); - const deleteTask = await client.waitForTask(enqueuedTask.taskUid); + const deleteTask = await client.tasks + .deleteTasks({ indexUids: [index.uid] }) + .waitTask(); - expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION); - await expect(client.getTask(addDocuments.taskUid)).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.TASK_NOT_FOUND, - ); + assert.strictEqual(deleteTask.type, "taskDeletion"); + await expect( + client.tasks.getTask(addDocuments.taskUid), + ).rejects.toHaveProperty("cause.code", ErrorStatusCode.TASK_NOT_FOUND); }); // delete: type test(`${permission} key: Delete a task using the type filter`, async () => { const client = await getClient(permission); - const enqueuedTask = await client.deleteTasks({ - types: [ - TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE, - TaskTypes.DOCUMENT_DELETION, - ], - }); - const deleteTask = await client.waitForTask(enqueuedTask.taskUid); + const deleteTask = await client.tasks + .deleteTasks({ + types: ["documentAdditionOrUpdate", "documentDeletion"], + }) + .waitTask(); - expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION); + assert.strictEqual(deleteTask.type, "taskDeletion"); expect(deleteTask.details?.originalFilter).toEqual( "?types=documentAdditionOrUpdate%2CdocumentDeletion", ); @@ -683,12 +616,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Delete a task using the status filter`, async () => { const client = await getClient(permission); - const enqueuedTask = await client.deleteTasks({ - statuses: [TaskStatus.TASK_ENQUEUED, TaskStatus.TASK_PROCESSING], - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .deleteTasks({ statuses: ["enqueued", "processing"] }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_DELETION); + assert.strictEqual(task.type, "taskDeletion"); expect(task.details?.originalFilter).toEqual( "?statuses=enqueued%2Cprocessing", ); @@ -700,12 +632,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.deleteTasks({ - beforeEnqueuedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .deleteTasks({ beforeEnqueuedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_DELETION); + assert.strictEqual(task.type, "taskDeletion"); expect(task.details?.originalFilter).toContain("beforeEnqueuedAt"); }); @@ -715,12 +646,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.deleteTasks({ - afterEnqueuedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .deleteTasks({ afterEnqueuedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_DELETION); + assert.strictEqual(task.type, "taskDeletion"); expect(task.details?.originalFilter).toContain("afterEnqueuedAt"); }); @@ -730,12 +660,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.deleteTasks({ - beforeStartedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .deleteTasks({ beforeStartedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_DELETION); + assert.strictEqual(task.type, "taskDeletion"); expect(task.details?.originalFilter).toContain("beforeStartedAt"); }); @@ -745,12 +674,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.deleteTasks({ - afterStartedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .deleteTasks({ afterStartedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_DELETION); + assert.strictEqual(task.type, "taskDeletion"); expect(task.details?.originalFilter).toContain("afterStartedAt"); }); @@ -760,12 +688,11 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.deleteTasks({ - beforeFinishedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .deleteTasks({ beforeFinishedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_DELETION); + assert.strictEqual(task.type, "taskDeletion"); expect(task.details?.originalFilter).toContain("beforeFinishedAt"); }); @@ -775,32 +702,18 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const currentTimeStamp = Date.now(); const currentTime = new Date(currentTimeStamp); - const enqueuedTask = await client.deleteTasks({ - afterFinishedAt: currentTime, - }); - const task = await client.waitForTask(enqueuedTask.taskUid); + const task = await client.tasks + .deleteTasks({ afterFinishedAt: currentTime.toISOString() }) + .waitTask(); - expect(task.type).toEqual(TaskTypes.TASK_DELETION); + assert.strictEqual(task.type, "taskDeletion"); expect(task.details?.originalFilter).toContain("afterFinishedAt"); }); - test(`${permission} key: Get all indexes tasks with index instance`, async () => { - const client = await getClient(permission); - await client.index(index.uid).addDocuments([{ id: 1 }]); - await client.index(index2.uid).addDocuments([{ id: 1 }]); - - const tasks = await client.index(index.uid).getTasks(); - const onlyTaskWithSameUid = new Set( - tasks.results.map((task) => task.indexUid), - ); - - expect(onlyTaskWithSameUid.size).toEqual(1); - }); - test(`${permission} key: Try to get a task that does not exist`, async () => { const client = await getClient(permission); - await expect(client.getTask(254500)).rejects.toHaveProperty( + await expect(client.tasks.getTask(254500)).rejects.toHaveProperty( "cause.code", ErrorStatusCode.TASK_NOT_FOUND, ); @@ -815,7 +728,7 @@ describe.each([{ permission: "Search" }])("Test on tasks", ({ permission }) => { test(`${permission} key: Try to get a task and be denied`, async () => { const client = await getClient(permission); - await expect(client.getTask(0)).rejects.toHaveProperty( + await expect(client.tasks.getTask(0)).rejects.toHaveProperty( "cause.code", ErrorStatusCode.INVALID_API_KEY, ); @@ -829,7 +742,7 @@ describe.each([{ permission: "No" }])("Test on tasks", ({ permission }) => { test(`${permission} key: Try to get an task and be denied`, async () => { const client = await getClient(permission); - await expect(client.getTask(0)).rejects.toHaveProperty( + await expect(client.tasks.getTask(0)).rejects.toHaveProperty( "cause.code", ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, ); @@ -846,7 +759,7 @@ describe.each([ const client = new MeiliSearch({ host }); const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.index(index.uid).getTask(1)).rejects.toHaveProperty( + await expect(client.tasks.getTask(1)).rejects.toHaveProperty( "message", `Request to ${strippedHost}/${route} has failed`, ); @@ -857,7 +770,9 @@ describe.each([ const client = new MeiliSearch({ host }); const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.index(index.uid).getTasks()).rejects.toHaveProperty( + await expect( + client.tasks.getTasks({ indexUids: ["movies_test"] }), + ).rejects.toHaveProperty( "message", `Request to ${strippedHost}/${route} has failed`, ); diff --git a/tests/token.test.ts b/tests/token.test.ts index d31790b56..349c95037 100644 --- a/tests/token.test.ts +++ b/tests/token.test.ts @@ -84,8 +84,7 @@ describe.each([{ permission: "Admin" }])( beforeEach(async () => { const client = await getClient("Master"); await client.index(UID).delete(); - const { taskUid } = await client.index(UID).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(UID).addDocuments(dataset).waitTask(); const keys = await client.getKeys(); @@ -298,10 +297,10 @@ describe.each([{ permission: "Admin" }])( test(`${permission} key: Search in tenant token with specific index and specific rules`, async () => { // add filterable const masterClient = await getClient("master"); - const { taskUid } = await masterClient + await masterClient .index(UID) - .updateFilterableAttributes(["id"]); - await masterClient.waitForTask(taskUid); + .updateFilterableAttributes(["id"]) + .waitTask(); const client = await getClient(permission); const apiKey = await getKey(permission); const { uid } = await client.getKey(apiKey); diff --git a/tests/typed_search.test.ts b/tests/typed_search.test.ts index 06467cfb2..a34381989 100644 --- a/tests/typed_search.test.ts +++ b/tests/typed_search.test.ts @@ -6,8 +6,7 @@ import { expect, test, } from "vitest"; -import { ErrorStatusCode, type SearchResponse } from "../src/types.js"; -import { EnqueuedTask } from "../src/enqueued-task.js"; +import { ErrorStatusCode, type SearchResponse } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -114,21 +113,16 @@ describe.each([ const client = await getClient("Master"); await clearAllIndexes(config); - const task1 = await client.createIndex(index.uid); - await client.waitForTask(task1.taskUid); - const task2 = await client.createIndex(emptyIndex.uid); - await client.waitForTask(task2.taskUid); + await client.createIndex(index.uid).waitTask(); + await client.createIndex(emptyIndex.uid).waitTask(); const newFilterableAttributes = ["genre", "title"]; - const task: EnqueuedTask = await client + await client .index(index.uid) - .updateFilterableAttributes(newFilterableAttributes); + .updateFilterableAttributes(newFilterableAttributes) + .waitTask(); - await client.waitForTask(task.taskUid); - const { taskUid } = await client - .index(index.uid) - .addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Basic search`, async () => { @@ -399,8 +393,7 @@ describe.each([ test(`${permission} key: Try to Search on deleted index and fail`, async () => { const client = await getClient(permission); const masterClient = await getClient("Master"); - const { taskUid } = await masterClient.index(index.uid).delete(); - await masterClient.waitForTask(taskUid); + await masterClient.index(index.uid).delete().waitTask(); await expect( client.index(index.uid).search("prince"), @@ -416,10 +409,7 @@ describe.each([{ permission: "Master" }])( const client = await getClient("Master"); await client.createIndex(index.uid); - const { taskUid: documentAdditionTask } = await client - .index(index.uid) - .addDocuments(datasetWithNests); - await client.waitForTask(documentAdditionTask); + await client.index(index.uid).addDocuments(datasetWithNests).waitTask(); }); test(`${permission} key: search on nested content with no parameters`, async () => { @@ -434,12 +424,12 @@ describe.each([{ permission: "Master" }])( test(`${permission} key: search on nested content with searchable on specific nested field`, async () => { const client = await getClient(permission); - const { taskUid: settingsUpdateTask }: EnqueuedTask = await client + await client .index(index.uid) .updateSettings({ searchableAttributes: ["title", "info.comment"], - }); - await client.waitForTask(settingsUpdateTask); + }) + .waitTask(); const response: SearchResponse = await client .index(index.uid) @@ -451,13 +441,13 @@ describe.each([{ permission: "Master" }])( test(`${permission} key: search on nested content with sort`, async () => { const client = await getClient(permission); - const { taskUid: settingsUpdateTask }: EnqueuedTask = await client + await client .index(index.uid) .updateSettings({ searchableAttributes: ["title", "info.comment"], sortableAttributes: ["info.reviewNb"], - }); - await client.waitForTask(settingsUpdateTask); + }) + .waitTask(); const response: SearchResponse = await client .index(index.uid) diff --git a/tests/typo_tolerance.test.ts b/tests/typo_tolerance.test.ts index 06ad08f50..7cad1e126 100644 --- a/tests/typo_tolerance.test.ts +++ b/tests/typo_tolerance.test.ts @@ -1,5 +1,5 @@ import { afterAll, beforeEach, describe, expect, test } from "vitest"; -import { ErrorStatusCode } from "../src/types.js"; +import { ErrorStatusCode } from "../src/types/index.js"; import { clearAllIndexes, config, @@ -33,8 +33,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("master"); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await client.waitForTask(taskUid); + await client.index(index.uid).addDocuments(dataset).waitTask(); }); test(`${permission} key: Get default typo tolerance settings`, async () => { @@ -54,10 +53,10 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( disableOnWords: ["title"], disableOnAttributes: ["hello"], }; - const task = await client + await client .index(index.uid) - .updateTypoTolerance(newTypoTolerance); - await client.index(index.uid).waitForTask(task.taskUid); + .updateTypoTolerance(newTypoTolerance) + .waitTask(); const response = await client.index(index.uid).getTypoTolerance(); @@ -66,8 +65,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Update typo tolerance using null as value`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).updateTypoTolerance(null); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).updateTypoTolerance(null).waitTask(); const response = await client.index(index.uid).getTypoTolerance(); @@ -76,8 +74,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( test(`${permission} key: Reset typo tolerance settings`, async () => { const client = await getClient(permission); - const task = await client.index(index.uid).resetTypoTolerance(); - await client.index(index.uid).waitForTask(task.taskUid); + await client.index(index.uid).resetTypoTolerance().waitTask(); const response = await client.index(index.uid).getTypoTolerance(); diff --git a/tests/utils/meilisearch-test-utils.ts b/tests/utils/meilisearch-test-utils.ts index 180cbe90f..39fc66b2b 100644 --- a/tests/utils/meilisearch-test-utils.ts +++ b/tests/utils/meilisearch-test-utils.ts @@ -1,15 +1,16 @@ import { assert as vitestAssert } from "vitest"; import { MeiliSearch, Index } from "../../src/index.js"; -import type { Config } from "../../src/types.js"; +import type { Config } from "../../src/types/index.js"; // testing const MASTER_KEY = "masterKey"; const HOST = process.env.MEILISEARCH_URL || "http://127.0.0.1:7700"; const BAD_HOST = "http://127.0.0.1:7701"; -const config = { +const config: Config = { host: HOST, apiKey: MASTER_KEY, + defaultWaitOptions: { interval: 10 }, }; const badHostClient = new MeiliSearch({ host: BAD_HOST, @@ -18,10 +19,12 @@ const badHostClient = new MeiliSearch({ const masterClient = new MeiliSearch({ host: HOST, apiKey: MASTER_KEY, + defaultWaitOptions: { interval: 10 }, }); const anonymousClient = new MeiliSearch({ host: HOST, + defaultWaitOptions: { interval: 10 }, }); async function getKey(permission: string): Promise { @@ -46,6 +49,7 @@ async function getClient(permission: string): Promise { if (permission === "No") { const anonymousClient = new MeiliSearch({ host: HOST, + defaultWaitOptions: { interval: 10 }, }); return anonymousClient; } @@ -55,6 +59,7 @@ async function getClient(permission: string): Promise { const searchClient = new MeiliSearch({ host: HOST, apiKey: searchKey, + defaultWaitOptions: { interval: 10 }, }); return searchClient; } @@ -64,6 +69,7 @@ async function getClient(permission: string): Promise { const adminClient = new MeiliSearch({ host: HOST, apiKey: adminKey, + defaultWaitOptions: { interval: 10 }, }); return adminClient; } @@ -73,16 +79,13 @@ async function getClient(permission: string): Promise { const clearAllIndexes = async (config: Config): Promise => { const client = new MeiliSearch(config); - const { results } = await client.getRawIndexes(); - const indexes = results.map(({ uid }) => uid); - const taskIds: number[] = []; - for (const indexUid of indexes) { - const { taskUid } = await client.index(indexUid).delete(); - taskIds.push(taskUid); - } - await client.waitForTasks(taskIds, { timeOutMs: 60_000 }); + await Promise.all( + results.map((v) => + client.index(v.uid).delete().waitTask({ timeout: 60_000 }), + ), + ); }; function decode64(buff: string) { diff --git a/tests/wait_for_task.test.ts b/tests/wait_for_task.test.ts index a554ae45c..95c33ff08 100644 --- a/tests/wait_for_task.test.ts +++ b/tests/wait_for_task.test.ts @@ -1,5 +1,4 @@ -import { afterAll, beforeEach, describe, expect, test } from "vitest"; -import { TaskStatus } from "../src/index.js"; +import { afterAll, beforeEach, describe, expect, test, assert } from "vitest"; import { clearAllIndexes, config, @@ -20,149 +19,125 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - const { taskUid } = await client.createIndex(index.uid); - await client.waitForTask(taskUid); + await client.createIndex(index.uid).waitTask(); }); // Client Wait for task test(`${permission} key: Tests wait for task in client until done and resolved`, async () => { const client = await getClient(permission); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - - const update = await client.waitForTask(taskUid); + const update = await client + .index(index.uid) + .addDocuments(dataset) + .waitTask(); - expect(update).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); + assert.strictEqual(update.status, "succeeded"); }); test(`${permission} key: Tests wait for task in client with custom interval and timeout until done and resolved`, async () => { const client = await getClient(permission); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - - const update = await client.waitForTask(taskUid, { - timeOutMs: 6000, - intervalMs: 100, - }); + const update = await client + .index(index.uid) + .addDocuments(dataset) + .waitTask({ + timeout: 6000, + interval: 100, + }); - expect(update).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); + assert.strictEqual(update.status, "succeeded"); }); test(`${permission} key: Tests wait for task in client with custom timeout and interval at 0 done and resolved`, async () => { const client = await getClient(permission); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - - const update = await client.waitForTask(taskUid, { - timeOutMs: 6000, - intervalMs: 0, - }); + const update = await client + .index(index.uid) + .addDocuments(dataset) + .waitTask({ + timeout: 6000, + interval: 0, + }); - expect(update).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); + assert.strictEqual(update.status, "succeeded"); }); test(`${permission} key: Try to wait for task in client with small timeout and raise an error`, async () => { const client = await getClient(permission); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - await expect( - client.waitForTask(taskUid, { timeOutMs: 0 }), - ).rejects.toHaveProperty("name", "MeiliSearchTimeOutError"); + client.index(index.uid).addDocuments(dataset).waitTask({ timeout: 1 }), + ).rejects.toHaveProperty("name", "MeiliSearchTaskTimeOutError"); }); // Index Wait for task test(`${permission} key: Tests wait for task with an index instance`, async () => { const client = await getClient(permission); - const { taskUid } = await client.index(index.uid).addDocuments(dataset); - - const update = await client.index(index.uid).waitForTask(taskUid); + const update = await client + .index(index.uid) + .addDocuments(dataset) + .waitTask(); - expect(update).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); + assert.strictEqual(update.status, "succeeded"); }); // Client Wait for tasks test(`${permission} key: Tests wait for tasks in client until done and resolved`, async () => { const client = await getClient(permission); - const { taskUid: task1 } = await client - .index(index.uid) - .addDocuments(dataset); - const { taskUid: task2 } = await client - .index(index.uid) - .addDocuments(dataset); + const task1 = await client.index(index.uid).addDocuments(dataset); + const task2 = await client.index(index.uid).addDocuments(dataset); - const tasks = await client.waitForTasks([task1, task2]); + const tasks = await client.tasks.waitForTasks([task1, task2]); const [update1, update2] = tasks; - expect(update1).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); - expect(update2).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); + assert.strictEqual(update1.status, "succeeded"); + assert.strictEqual(update2.status, "succeeded"); }); test(`${permission} key: Tests wait for tasks in client with custom interval and timeout until done and resolved`, async () => { const client = await getClient(permission); - const { taskUid: task1 } = await client - .index(index.uid) - .addDocuments(dataset); - const { taskUid: task2 } = await client - .index(index.uid) - .addDocuments(dataset); + const task1 = await client.index(index.uid).addDocuments(dataset); + const task2 = await client.index(index.uid).addDocuments(dataset); - const tasks = await client.waitForTasks([task1, task2], { - timeOutMs: 6000, - intervalMs: 100, + const tasks = await client.tasks.waitForTasks([task1, task2], { + timeout: 6000, + interval: 100, }); const [update1, update2] = tasks; - expect(update1).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); - expect(update2).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); + assert.strictEqual(update1.status, "succeeded"); + assert.strictEqual(update2.status, "succeeded"); }); test(`${permission} key: Tests wait for tasks in client with custom timeout and interval at 0 done and resolved`, async () => { const client = await getClient(permission); - const { taskUid: task1 } = await client - .index(index.uid) - .addDocuments(dataset); - const { taskUid: task2 } = await client - .index(index.uid) - .addDocuments(dataset); + const task1 = await client.index(index.uid).addDocuments(dataset); + const task2 = await client.index(index.uid).addDocuments(dataset); - const tasks = await client.waitForTasks([task1, task2], { - timeOutMs: 6000, - intervalMs: 0, + const tasks = await client.tasks.waitForTasks([task1, task2], { + timeout: 6000, + interval: 0, }); const [update1, update2] = tasks; - expect(update1).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); - expect(update2).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); + assert.strictEqual(update1.status, "succeeded"); + assert.strictEqual(update2.status, "succeeded"); }); test(`${permission} key: Tests to wait for tasks in client with small timeout and raise an error`, async () => { const client = await getClient(permission); - const { taskUid: task1 } = await client - .index(index.uid) - .addDocuments(dataset); - const { taskUid: task2 } = await client - .index(index.uid) - .addDocuments(dataset); + const task1 = await client.index(index.uid).addDocuments(dataset); + const task2 = await client.index(index.uid).addDocuments(dataset); await expect( - client.waitForTasks([task1, task2], { timeOutMs: 0 }), - ).rejects.toHaveProperty("name", "MeiliSearchTimeOutError"); + client.tasks.waitForTasks([task1, task2], { timeout: 1 }), + ).rejects.toHaveProperty("name", "MeiliSearchTaskTimeOutError"); }); - // Index Wait for tasks - test(`${permission} key: Tests wait for tasks with indx instance`, async () => { + test(`${permission} key: Tests to wait for task that doesn't exist`, async () => { const client = await getClient(permission); - const { taskUid: task1 } = await client - .index(index.uid) - .addDocuments(dataset); - const { taskUid: task2 } = await client - .index(index.uid) - .addDocuments(dataset); - const tasks = await client.index(index.uid).waitForTasks([task1, task2]); - const [update1, update2] = tasks; - - expect(update1).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); - expect(update2).toHaveProperty("status", TaskStatus.TASK_SUCCEEDED); + await expect( + client.tasks.waitForTask(424242424242), + ).rejects.toHaveProperty("name", "MeiliSearchApiError"); }); }, );