Skip to content

Commit

Permalink
Convert props to private, refactor, adapt tests
Browse files Browse the repository at this point in the history
  • Loading branch information
flevi29 committed Oct 9, 2024
1 parent 9f41065 commit a32ed2d
Show file tree
Hide file tree
Showing 9 changed files with 455 additions and 453 deletions.
59 changes: 25 additions & 34 deletions src/clients/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class Client {
* @returns Promise returning array of raw index information
*/
async getIndexes(
parameters: IndexesQuery = {},
parameters?: IndexesQuery,
): Promise<IndexesResults<Index[]>> {
const rawIndexes = await this.getRawIndexes(parameters);
const indexes: Index[] = rawIndexes.results.map(
Expand All @@ -114,11 +114,10 @@ class Client {
* @returns Promise returning array of raw index information
*/
async getRawIndexes(
parameters: IndexesQuery = {},
parameters?: IndexesQuery,
): Promise<IndexesResults<IndexObject[]>> {
const url = `indexes`;
return <IndexesResults<IndexObject[]>>(
await this.httpRequest.get({ relativeURL: url, params: parameters })
await this.httpRequest.get({ relativeURL: "indexes", params: parameters })
);
}

Expand All @@ -131,7 +130,7 @@ class Client {
*/
async createIndex(
uid: string,
options: IndexOptions = {},
options?: IndexOptions,
): Promise<EnqueuedTask> {
return await Index.create(uid, options, this.config);
}
Expand All @@ -145,7 +144,7 @@ class Client {
*/
async updateIndex(
uid: string,
options: IndexOptions = {},
options?: IndexOptions,
): Promise<EnqueuedTask> {
return await new Index(this.config, uid).update(options);
}
Expand Down Expand Up @@ -231,10 +230,11 @@ class Client {
queries: MultiSearchParams | FederatedMultiSearchParams,
config?: Partial<Request>,

Check failure on line 231 in src/clients/client.ts

View workflow job for this annotation

GitHub Actions / style-check

'config' is defined but never used. Allowed unused args must match /^_/u
): Promise<MultiSearchResponse<T> | SearchResponse<T>> {
const url = `multi-search`;

return <MultiSearchResponse<T> | SearchResponse<T>>(
await this.httpRequest.post({ relativeURL: url, body: queries })
await this.httpRequest.post({
relativeURL: "multi-search",
body: queries,
})
);
}

Expand All @@ -248,7 +248,7 @@ class Client {
* @param parameters - Parameters to browse the tasks
* @returns Promise returning all tasks
*/
async getTasks(parameters: TasksQuery = {}): Promise<TasksResults> {
async getTasks(parameters?: TasksQuery): Promise<TasksResults> {
return await this.tasks.getTasks(parameters);
}

Expand Down Expand Up @@ -312,7 +312,7 @@ class Client {
* @param parameters - Parameters to filter the tasks.
* @returns Promise containing an EnqueuedTask
*/
async deleteTasks(parameters: DeleteTasksQuery = {}): Promise<EnqueuedTask> {
async deleteTasks(parameters?: DeleteTasksQuery): Promise<EnqueuedTask> {
return await this.tasks.deleteTasks(parameters);
}

Expand All @@ -326,10 +326,9 @@ class Client {
* @param parameters - Parameters to browse the indexes
* @returns Promise returning an object with keys
*/
async getKeys(parameters: KeysQuery = {}): Promise<KeysResults> {
const url = `keys`;
async getKeys(parameters?: KeysQuery): Promise<KeysResults> {
const keys = <KeysResults>(
await this.httpRequest.get({ relativeURL: url, params: parameters })
await this.httpRequest.get({ relativeURL: "keys", params: parameters })
);

keys.results = keys.results.map((key) => ({
Expand All @@ -348,8 +347,7 @@ class Client {
* @returns Promise returning a key
*/
async getKey(keyOrUid: string): Promise<Key> {
const url = `keys/${keyOrUid}`;
return <Key>await this.httpRequest.get({ relativeURL: url });
return <Key>await this.httpRequest.get({ relativeURL: `keys/${keyOrUid}` });
}

/**
Expand All @@ -359,9 +357,8 @@ class Client {
* @returns Promise returning a key
*/
async createKey(options: KeyCreation): Promise<Key> {
const url = `keys`;
return <Key>(
await this.httpRequest.post({ relativeURL: url, body: options })
await this.httpRequest.post({ relativeURL: "keys", body: options })
);
}

Expand All @@ -373,10 +370,10 @@ class Client {
* @returns Promise returning a key
*/
async updateKey(keyOrUid: string, options: KeyUpdate): Promise<Key> {
const url = `keys/${keyOrUid}`;
return <Key>(
await this.httpRequest.patch({ relativeURL: url, body: options })
);
return <Key>await this.httpRequest.patch({
relativeURL: `keys/${keyOrUid}`,
body: options,
});
}

/**
Expand All @@ -386,8 +383,7 @@ class Client {
* @returns
*/
async deleteKey(keyOrUid: string): Promise<void> {
const url = `keys/${keyOrUid}`;
await this.httpRequest.delete({ relativeURL: url });
await this.httpRequest.delete({ relativeURL: `keys/${keyOrUid}` });
}

///
Expand All @@ -400,8 +396,7 @@ class Client {
* @returns Promise returning an object with health details
*/
async health(): Promise<Health> {
const url = `health`;
return <Health>await this.httpRequest.get({ relativeURL: url });
return <Health>await this.httpRequest.get({ relativeURL: "health" });
}

/**
Expand All @@ -428,8 +423,7 @@ class Client {
* @returns Promise returning object of all the stats
*/
async getStats(): Promise<Stats> {
const url = `stats`;
return <Stats>await this.httpRequest.get({ relativeURL: url });
return <Stats>await this.httpRequest.get({ relativeURL: "stats" });
}

///
Expand All @@ -442,8 +436,7 @@ class Client {
* @returns Promise returning object with version details
*/
async getVersion(): Promise<Version> {
const url = `version`;
return <Version>await this.httpRequest.get({ relativeURL: url });
return <Version>await this.httpRequest.get({ relativeURL: "version" });
}

///
Expand All @@ -456,9 +449,8 @@ class Client {
* @returns Promise returning object of the enqueued task
*/
async createDump(): Promise<EnqueuedTask> {
const url = `dumps`;
const task = <EnqueuedTaskObject>(
await this.httpRequest.post({ relativeURL: url })
await this.httpRequest.post({ relativeURL: "dumps" })
);
return new EnqueuedTask(task);
}
Expand All @@ -473,9 +465,8 @@ class Client {
* @returns Promise returning object of the enqueued task
*/
async createSnapshot(): Promise<EnqueuedTask> {
const url = `snapshots`;
const task = <EnqueuedTaskObject>(
await this.httpRequest.post({ relativeURL: url })
await this.httpRequest.post({ relativeURL: "snapshots" })
);

return new EnqueuedTask(task);
Expand Down
46 changes: 20 additions & 26 deletions src/http-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
MeiliSearchRequestError,
} from "./errors";

import { addTrailingSlash, addProtocolIfNotPresent } from "./utils";
import { addProtocolIfNotPresent, addTrailingSlash } from "./utils";

type URLSearchParamsRecord = Record<
string,
Expand Down Expand Up @@ -74,12 +74,6 @@ function getHeaders(config: Config, headersInit?: HeadersInit): Headers {
return headers;
}

function constructHostURL(host: string): string {
host = addProtocolIfNotPresent(host);
host = addTrailingSlash(host);
return host;
}

type RequestOptions = {
relativeURL: string;
method?: string;
Expand All @@ -91,50 +85,50 @@ type RequestOptions = {
export type MethodOptions = Omit<RequestOptions, "method">;

export class HttpRequests {
url: URL;
requestInit: Omit<NonNullable<Config["requestInit"]>, "headers"> & {
#url: URL;
#requestInit: Omit<NonNullable<Config["requestInit"]>, "headers"> & {
headers: Headers;
};
httpClient: Config["httpClient"];
requestTimeout?: number;
#requestFn: NonNullable<Config["httpClient"]>;
#isCustomRequestFnProvided: boolean;
#requestTimeout?: number;

constructor(config: Config) {
const host = constructHostURL(config.host);
const host = addTrailingSlash(addProtocolIfNotPresent(config.host));

try {
this.url = new URL(host);
this.#url = new URL(host);
} catch (error) {
throw new MeiliSearchError("The provided host is not valid", {
cause: error,
});
}

this.requestInit = {
this.#requestInit = {
...config.requestInit,
headers: getHeaders(config, config.requestInit?.headers),
};

this.httpClient = config.httpClient;
this.requestTimeout = config.timeout;
this.#requestFn = config.httpClient ?? fetch;
this.#isCustomRequestFnProvided = config.httpClient !== undefined;
this.#requestTimeout = config.timeout;
}

async #fetchWithTimeout(
...fetchParams: Parameters<typeof fetch>
): Promise<Response> {
return new Promise((resolve, reject) => {
const fetchFn = this.httpClient ? this.httpClient : fetch;

const fetchPromise = fetchFn(...fetchParams);
const fetchPromise = this.#requestFn(...fetchParams);

const promises: Array<Promise<any>> = [fetchPromise];

// TimeoutPromise will not run if undefined or zero
let timeoutId: ReturnType<typeof setTimeout>;
if (this.requestTimeout) {
if (this.#requestTimeout) {
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(() => {
reject(new Error("Error: Request Timed Out"));
}, this.requestTimeout);
}, this.#requestTimeout);
});

promises.push(timeoutPromise);
Expand All @@ -156,7 +150,7 @@ export class HttpRequests {
headers,
body,
}: RequestOptions): Promise<unknown> {
const url = new URL(relativeURL, this.url);
const url = new URL(relativeURL, this.#url);
if (params !== undefined) {
appendRecordToURLSearchParams(url.searchParams, params);
}
Expand All @@ -168,7 +162,7 @@ export class HttpRequests {

isCustomContentTypeProvided = headers.has("Content-Type");

for (const [key, val] of this.requestInit.headers.entries()) {
for (const [key, val] of this.#requestInit.headers.entries()) {
if (!headers.has(key)) {
headers.set(key, val);
}
Expand All @@ -185,16 +179,16 @@ export class HttpRequests {
? // this will throw an error for any value that is not serializable
JSON.stringify(body)
: body,
...this.requestInit,
headers: headers ?? this.requestInit.headers,
...this.#requestInit,
headers: headers ?? this.#requestInit.headers,
});

const response = await responsePromise.catch((error: unknown) => {
throw new MeiliSearchRequestError(url.toString(), error);
});

// When using a custom HTTP client, the response is returned to allow the user to parse/handle it as they see fit
if (this.httpClient !== undefined) {
if (this.#isCustomRequestFnProvided) {
return response;
}

Expand Down
Loading

0 comments on commit a32ed2d

Please sign in to comment.