Skip to content

Un-deprecate Config.httpClient and improve it #1979

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/errors/meilisearch-api-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,22 @@ import { MeiliSearchError } from "./meilisearch-error.js";
export class MeiliSearchApiError extends MeiliSearchError {
override name = "MeiliSearchApiError";
override cause?: MeiliSearchErrorResponse;
readonly response: Response;
readonly details: unknown;

constructor(response: Response, responseBody?: MeiliSearchErrorResponse) {
constructor(
responseBodyOrMessage: MeiliSearchErrorResponse | string,
details: unknown,
) {
super(
responseBody?.message ?? `${response.status}: ${response.statusText}`,
typeof responseBodyOrMessage === "string"
? responseBodyOrMessage
: responseBodyOrMessage.message,
);

this.response = response;
this.details = details;

if (responseBody !== undefined) {
this.cause = responseBody;
if (typeof responseBodyOrMessage !== "string") {
this.cause = responseBodyOrMessage;
}
}
}
15 changes: 12 additions & 3 deletions src/http-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,17 @@ export class HttpRequests {

let response: Response;
let responseBody: string;

try {
if (this.#customRequestFn !== undefined) {
// When using a custom HTTP client, the response should already be handled and ready to be returned
return (await this.#customRequestFn(url, init)) as T;
// when using custom HTTP client, response is handled differently
const resp = await this.#customRequestFn(url, init);

if (!resp.success) {
throw new MeiliSearchApiError(resp.value, resp.details);
}

return resp.value as T;
}

response = await fetch(url, init);
Expand All @@ -254,8 +261,10 @@ export class HttpRequests {

if (!response.ok) {
throw new MeiliSearchApiError(
parsedResponse === undefined
? `${response.status}: ${response.statusText}`
: (parsedResponse as MeiliSearchErrorResponse),
response,
parsedResponse as MeiliSearchErrorResponse | undefined,
);
}

Expand Down
37 changes: 29 additions & 8 deletions src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ export type HttpRequestsRequestInit = Omit<BaseRequestInit, "headers"> & {
headers: Headers;
};

/**
* An object in which `success` boolean indicates whether the response was
* successful (status 200-299), `value` is the parsed response body or a string
* describing the error in case there is no response body and `details` is any
* details about the error on failure.
*/
export type CustomHttpClientResult =
| { success: true; value: unknown }
| {
success: false;
value: MeiliSearchErrorResponse | string;
details: unknown;
};

/** Main configuration object for the meilisearch client. */
export type Config = {
/**
Expand All @@ -59,21 +73,28 @@ export type Config = {
*/
apiKey?: string;
/**
* Custom strings that will be concatted to the "X-Meilisearch-Client" header
* on each request.
* Custom strings that will be concatenated to the "X-Meilisearch-Client"
* header on each request.
*/
clientAgents?: string[];
/** Base request options that may override the default ones. */
requestInit?: BaseRequestInit;
/**
* Custom function that can be provided in place of {@link fetch}.
* Custom function that can be provided to make requests to Meilisearch.
*
* @remarks
* API response errors will have to be handled manually with this as well.
* @deprecated This will be removed in a future version. See
* {@link https://github.com/meilisearch/meilisearch-js/issues/1824 | issue}.
* Expects a {@link CustomHttpClientResult}, an object in which `success`
* boolean indicates whether the response was successful (status 200-299),
* `value` is the parsed response body or a string describing the error in
* case there is no response body and `details` is any details about the error
* on failure.
*
* By default
* {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API | fetch}
* is used.
*/
httpClient?: (...args: Parameters<typeof fetch>) => Promise<unknown>;
httpClient?: (
...args: Parameters<typeof fetch>
) => Promise<CustomHttpClientResult>;
/** Timeout in milliseconds for each HTTP request. */
timeout?: number;
/** Customizable default options for awaiting tasks. */
Expand Down
54 changes: 50 additions & 4 deletions tests/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,18 @@ import {
type MockInstance,
beforeAll,
} from "vitest";
import type { Health, Version, Stats, IndexSwap } from "../src/index.js";
import { ErrorStatusCode, MeiliSearchRequestError } from "../src/index.js";
import type {
Health,
Version,
Stats,
IndexSwap,
MeiliSearchErrorResponse,
} from "../src/index.js";
import {
ErrorStatusCode,
MeiliSearchApiError,
MeiliSearchRequestError,
} from "../src/index.js";
import { PACKAGE_VERSION } from "../src/package-version.js";
import {
clearAllIndexes,
Expand Down Expand Up @@ -269,9 +279,14 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])(
const client = new MeiliSearch({
...config,
apiKey: key,
async httpClient(...params: Parameters<typeof fetch>) {
async httpClient(...params) {
const result = await fetch(...params);
return result.json() as Promise<unknown>;

if (!result.ok) {
throw new Error("expected custom HTTP client to not fail");
}

return { success: true, value: result.json() as Promise<unknown> };
},
});
const health = await client.isHealthy();
Expand All @@ -292,6 +307,37 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])(
expect(documents.length).toBe(1);
});

test(`${permission} key: Create client with custom http client that fails`, async () => {
const key = await getKey(permission);
const client = new MeiliSearch({
...config,
apiKey: key,
async httpClient(...params) {
const response = await fetch(...params);

if (response.ok) {
throw new Error("expected custom HTTP client to fail");
}

const text = await response.text();

const value =
text === ""
? "(no response body)"
: (JSON.parse(text) as MeiliSearchErrorResponse);

return { success: false, value, details: response };
},
});

const error = await assert.rejects(
client.multiSearch({ queries: [{ indexUid: crypto.randomUUID() }] }),
MeiliSearchRequestError,
);

assert.instanceOf(error.cause, MeiliSearchApiError);
});

describe("Header tests", () => {
let fetchSpy: MockInstance<typeof fetch>;

Expand Down