Skip to content

Commit 780e469

Browse files
flevi29Strift
andauthored
Improve TaskClient, BatchClient and associated types (#1825)
* Remove unnecessary classes * Save progress * Progress * Progress * Fix formatting * Fix test * Fix test * Fix rest of the tests, adjust readme * Add documentation, adjust types, functions, misc * Fix formatting * Revert some changes, misc * Adjust types * Fix test * Misc * Adjust docs * Adjust doc * Revert settings types change * Fix formatting * Add task wait applier to tasks as well * Revert bad test * Remove focus from test, experiment with old interval * Fix not clearing timers when task is successfully awaited * Try and fix waitTask being slow * Fix unhandled rejections * Refactor waitTask * Try fix slow waitTask * Try fix slow waitTask * Add ability to specify default wait options for tasks through exported classes, use lower interval in tests * Shorten code * Rename variables * Remove hint about bad Meilisearch version * Add test for failing waitTask * Fix formatting, don't add timeout if interval is invalid * Rename functions, adjust description * Do not export TaskClient in index * Revert deprecations * Fix formatting * Added missing batchUids prop, misc * Make waitTask abort last getTask on timeout * Improve timeout errors, fix tests * Misc * Fix error * Fix formatting * Remove unnecessary tests * Fix waitTask, try Symbol for timeout ID * Fix http requests not catching abort error on response.text() * Fix Node.js 18 compat * Add documentation to changed errors * Update type definitions header --------- Co-authored-by: Laurent Cazanove <[email protected]>
1 parent 5c418fb commit 780e469

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

65 files changed

+1659
-2503
lines changed

README.md

Lines changed: 2 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -564,34 +564,16 @@ client.index('myIndex').getTasks(parameters: TasksQuery): Promise<TasksResults>
564564
client.index('myIndex').getTask(uid: number): Promise<Task>
565565
```
566566

567-
568567
#### Wait for one task
569568

570-
571-
##### Using the client
572-
573-
```ts
574-
client.waitForTask(uid: number, { timeOutMs?: number, intervalMs?: number }): Promise<Task>
575-
```
576-
577-
##### Using the index
578-
579569
```ts
580-
client.index('myIndex').waitForTask(uid: number, { timeOutMs?: number, intervalMs?: number }): Promise<Task>
570+
client.tasks.waitForTask(uid: number, { timeout?: number, interval?: number }): Promise<Task>
581571
```
582572

583573
#### Wait for multiple tasks
584574

585-
##### Using the client
586-
587-
```ts
588-
client.waitForTasks(uids: number[], { timeOutMs?: number, intervalMs?: number }): Promise<Task[]>
589-
```
590-
591-
##### Using the index
592-
593575
```ts
594-
client.index('myIndex').waitForTasks(uids: number[], { timeOutMs?: number, intervalMs?: number }): Promise<Task[]>
576+
client.tasks.waitForTasks(uids: number[], { timeout?: number, interval?: number }): Promise<Task[]>
595577
```
596578

597579
### Batches <!-- omit in toc -->

playgrounds/javascript/src/meilisearch.ts

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,23 +12,22 @@ const index = client.index<{ id: number; title: string; genres: string[] }>(
1212
export async function addDocuments(): Promise<void> {
1313
await client.deleteIndexIfExists(indexUid);
1414

15-
const task1 = await client.createIndex(indexUid);
16-
await client.waitForTask(task1.taskUid);
17-
18-
const task2 = await index.addDocuments([
19-
{ id: 1, title: "Carol", genres: ["Romance", "Drama"] },
20-
{ id: 2, title: "Wonder Woman", genres: ["Action", "Adventure"] },
21-
{ id: 3, title: "Life of Pi", genres: ["Adventure", "Drama"] },
22-
{
23-
id: 4,
24-
title: "Mad Max: Fury Road",
25-
genres: ["Adventure", "Science Fiction"],
26-
},
27-
{ id: 5, title: "Moana", genres: ["Fantasy", "Action"] },
28-
{ id: 6, title: "Philadelphia", genres: ["Drama"] },
29-
]);
30-
31-
await client.index(indexUid).waitForTask(task2.taskUid);
15+
await client.createIndex(indexUid).waitTask();
16+
17+
await index
18+
.addDocuments([
19+
{ id: 1, title: "Carol", genres: ["Romance", "Drama"] },
20+
{ id: 2, title: "Wonder Woman", genres: ["Action", "Adventure"] },
21+
{ id: 3, title: "Life of Pi", genres: ["Adventure", "Drama"] },
22+
{
23+
id: 4,
24+
title: "Mad Max: Fury Road",
25+
genres: ["Adventure", "Science Fiction"],
26+
},
27+
{ id: 5, title: "Moana", genres: ["Fantasy", "Action"] },
28+
{ id: 6, title: "Philadelphia", genres: ["Drama"] },
29+
])
30+
.waitTask();
3231
}
3332

3433
export async function getAllHits(element: HTMLDivElement): Promise<void> {

src/batch.ts

Lines changed: 24 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,38 @@
11
import type {
2-
Config,
3-
BatchObject,
4-
BatchesQuery,
2+
Batch,
53
BatchesResults,
6-
BatchesResultsObject,
7-
} from "./types.js";
8-
import { HttpRequests } from "./http-requests.js";
9-
10-
class Batch {
11-
uid: BatchObject["uid"];
12-
details: BatchObject["details"];
13-
stats: BatchObject["stats"];
14-
startedAt: BatchObject["startedAt"];
15-
finishedAt: BatchObject["finishedAt"];
16-
duration: BatchObject["duration"];
17-
progress: BatchObject["progress"];
18-
19-
constructor(batch: BatchObject) {
20-
this.uid = batch.uid;
21-
this.details = batch.details;
22-
this.stats = batch.stats;
23-
this.startedAt = batch.startedAt;
24-
this.finishedAt = batch.finishedAt;
25-
this.duration = batch.duration;
26-
this.progress = batch.progress;
27-
}
28-
}
29-
30-
class BatchClient {
31-
httpRequest: HttpRequests;
32-
33-
constructor(config: Config) {
34-
this.httpRequest = new HttpRequests(config);
4+
TasksOrBatchesQuery,
5+
} from "./types/index.js";
6+
import type { HttpRequests } from "./http-requests.js";
7+
8+
/**
9+
* Class for handling batches.
10+
*
11+
* @see {@link https://www.meilisearch.com/docs/reference/api/batches}
12+
*/
13+
export class BatchClient {
14+
readonly #httpRequest: HttpRequests;
15+
16+
constructor(httpRequests: HttpRequests) {
17+
this.#httpRequest = httpRequests;
3518
}
3619

37-
/**
38-
* Get one batch
39-
*
40-
* @param uid - Unique identifier of the batch
41-
* @returns
42-
*/
20+
/** {@link https://www.meilisearch.com/docs/reference/api/batches#get-one-batch} */
4321
async getBatch(uid: number): Promise<Batch> {
44-
const batch = await this.httpRequest.get<BatchObject>({
22+
const batch = await this.#httpRequest.get<Batch>({
4523
path: `batches/${uid}`,
4624
});
47-
return new Batch(batch);
25+
return batch;
4826
}
4927

50-
/**
51-
* Get batches
52-
*
53-
* @param parameters - Parameters to browse the batches
54-
* @returns Promise containing all batches
55-
*/
56-
async getBatches(batchesQuery?: BatchesQuery): Promise<BatchesResults> {
57-
const batches = await this.httpRequest.get<BatchesResultsObject>({
28+
/** {@link https://www.meilisearch.com/docs/reference/api/batches#get-batches} */
29+
async getBatches(
30+
batchesQuery?: TasksOrBatchesQuery,
31+
): Promise<BatchesResults> {
32+
const batches = await this.#httpRequest.get<BatchesResults>({
5833
path: "batches",
5934
params: batchesQuery,
6035
});
61-
62-
return {
63-
...batches,
64-
results: batches.results.map((batch) => new Batch(batch)),
65-
};
36+
return batches;
6637
}
6738
}
68-
69-
export { BatchClient, Batch };

src/enqueued-task.ts

Lines changed: 0 additions & 19 deletions
This file was deleted.

src/errors/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export * from "./meilisearch-api-error.js";
22
export * from "./meilisearch-request-error.js";
33
export * from "./meilisearch-error.js";
4-
export * from "./meilisearch-timeout-error.js";
4+
export * from "./meilisearch-request-timeout-error.js";
5+
export * from "./meilisearch-task-timeout-error.js";

src/errors/meilisearch-api-error.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { MeiliSearchErrorResponse } from "../types.js";
1+
import type { MeiliSearchErrorResponse } from "../types/index.js";
22
import { MeiliSearchError } from "./meilisearch-error.js";
33

44
export class MeiliSearchApiError extends MeiliSearchError {

src/errors/meilisearch-error.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
11
export class MeiliSearchError extends Error {
22
override name = "MeiliSearchError";
3-
4-
constructor(...params: ConstructorParameters<typeof Error>) {
5-
super(...params);
6-
}
73
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { MeiliSearchError } from "./meilisearch-error.js";
2+
3+
/** Error thrown when a HTTP request times out. */
4+
export class MeiliSearchRequestTimeOutError extends MeiliSearchError {
5+
override name = "MeiliSearchRequestTimeOutError";
6+
override cause: { timeout: number; requestInit: RequestInit };
7+
8+
constructor(timeout: number, requestInit: RequestInit) {
9+
super(`request timed out after ${timeout}ms`);
10+
11+
this.cause = { timeout, requestInit };
12+
}
13+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { MeiliSearchError } from "./meilisearch-error.js";
2+
3+
/** Error thrown when a waiting for a task times out. */
4+
export class MeiliSearchTaskTimeOutError extends MeiliSearchError {
5+
override name = "MeiliSearchTaskTimeOutError";
6+
override cause: { taskUid: number; timeout: number };
7+
8+
constructor(taskUid: number, timeout: number) {
9+
super(
10+
`timeout of ${timeout}ms has exceeded on task ${taskUid} when waiting for it to be resolved.`,
11+
);
12+
13+
this.cause = { taskUid, timeout };
14+
}
15+
}

src/errors/meilisearch-timeout-error.ts

Lines changed: 0 additions & 9 deletions
This file was deleted.

src/http-requests.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ import type {
55
MainRequestOptions,
66
URLSearchParamsRecord,
77
MeiliSearchErrorResponse,
8-
} from "./types.js";
8+
} from "./types/index.js";
99
import { PACKAGE_VERSION } from "./package-version.js";
1010
import {
1111
MeiliSearchError,
1212
MeiliSearchApiError,
1313
MeiliSearchRequestError,
14+
MeiliSearchRequestTimeOutError,
1415
} from "./errors/index.js";
1516
import { addProtocolIfNotPresent, addTrailingSlash } from "./utils.js";
1617

@@ -79,7 +80,7 @@ const TIMEOUT_ID = {};
7980
* @remarks
8081
* This could be a short few straight forward lines using {@link AbortSignal.any}
8182
* and {@link AbortSignal.timeout}, but these aren't yet widely supported enough,
82-
* nor polyfillable, at the time of writing.
83+
* nor polyfill -able, at the time of writing.
8384
* @returns A new function which starts the timeout, which then returns another
8485
* function that clears the timeout
8586
*/
@@ -240,9 +241,7 @@ export class HttpRequests {
240241
throw new MeiliSearchRequestError(
241242
url.toString(),
242243
Object.is(error, TIMEOUT_ID)
243-
? new Error(`request timed out after ${this.#requestTimeout}ms`, {
244-
cause: init,
245-
})
244+
? new MeiliSearchRequestTimeOutError(this.#requestTimeout!, init)
246245
: error,
247246
);
248247
} finally {

src/index.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
export * from "./types.js";
1+
export * from "./types/index.js";
22
export * from "./errors/index.js";
33
export * from "./indexes.js";
4-
export * from "./enqueued-task.js";
5-
export * from "./task.js";
64
import { MeiliSearch } from "./meilisearch.js";
75

86
/**

0 commit comments

Comments
 (0)