Skip to content
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

Improve HttpRequests #1741

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"test": "vitest run --coverage",
"types:watch": "nodemon --config nodemon.json",
"types": "yarn tsc",
"test:env:browser": "yarn build && yarn --cwd tests/env/express && yarn --cwd tests/env/express test",
"test:env:browser": "yarn build && node scripts/copy-umd-file.js --to ./tests/env/express/public && yarn --cwd tests/env/express && yarn --cwd tests/env/express test",
"test:watch": "vitest watch",
"test:coverage": "yarn test",
"test:ci": "yarn test",
Expand Down
16 changes: 16 additions & 0 deletions scripts/copy-umd-file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { parseArgs } = require("node:util");
const { resolve, join, basename } = require("node:path");
const { copyFileSync } = require("node:fs");
const pkg = require("../package.json");

const {
values: { to },
} = parseArgs({ options: { to: { type: "string" } } });

if (to === undefined) {
throw new Error("required argument `to` missing");
}

const umdAbsolutePath = resolve(__dirname, join("..", pkg.jsdelivr));

copyFileSync(umdAbsolutePath, join(to, basename(pkg.jsdelivr)));
147 changes: 75 additions & 72 deletions src/clients/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,21 @@ import {
ErrorStatusCode,
TokenSearchRules,
TokenOptions,
TasksQuery,
WaitOptions,
KeyUpdate,
IndexesQuery,
IndexesResults,
KeysQuery,
KeysResults,
TasksResults,
EnqueuedTaskObject,
SwapIndexesParams,
CancelTasksQuery,
DeleteTasksQuery,
MultiSearchParams,
MultiSearchResponse,
SearchResponse,
FederatedMultiSearchParams,
ExtraRequestInit,
} from "../types";
import { HttpRequests } from "../http-requests";
import { TaskClient, Task } from "../task";
import { TaskClient } from "../task";
import { EnqueuedTask } from "../enqueued-task";

class Client {
Expand Down Expand Up @@ -98,7 +94,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,13 +110,12 @@ class Client {
* @returns Promise returning array of raw index information
*/
async getRawIndexes(
parameters: IndexesQuery = {},
parameters?: IndexesQuery,
): Promise<IndexesResults<IndexObject[]>> {
const url = `indexes`;
return await this.httpRequest.get<IndexesResults<IndexObject[]>>(
url,
parameters,
);
return (await this.httpRequest.get({
relativeURL: "indexes",
params: parameters,
})) as IndexesResults<IndexObject[]>;
}

/**
Expand All @@ -132,7 +127,7 @@ class Client {
*/
async createIndex(
uid: string,
options: IndexOptions = {},
options?: IndexOptions,
): Promise<EnqueuedTask> {
return await Index.create(uid, options, this.config);
}
Expand All @@ -146,7 +141,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 @@ -188,7 +183,12 @@ class Client {
*/
async swapIndexes(params: SwapIndexesParams): Promise<EnqueuedTask> {
const url = "/swap-indexes";
return await this.httpRequest.post(url, params);
const taks = (await this.httpRequest.post({
relativeURL: url,
body: params,
})) as EnqueuedTaskObject;

return new EnqueuedTask(taks);
}
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug: previously this did not return EnqueuedTask, but rather EnqueuedTaskObject


///
Expand Down Expand Up @@ -218,19 +218,21 @@ class Client {
*/
multiSearch<T extends Record<string, unknown> = Record<string, any>>(
queries: MultiSearchParams,
config?: Partial<Request>,
extraRequestInit?: ExtraRequestInit,
): Promise<MultiSearchResponse<T>>;
multiSearch<T extends Record<string, unknown> = Record<string, any>>(
queries: FederatedMultiSearchParams,
config?: Partial<Request>,
extraRequestInit?: ExtraRequestInit,
): Promise<SearchResponse<T>>;
async multiSearch<T extends Record<string, unknown> = Record<string, any>>(
queries: MultiSearchParams | FederatedMultiSearchParams,
config?: Partial<Request>,
extraRequestInit?: ExtraRequestInit,
): Promise<MultiSearchResponse<T> | SearchResponse<T>> {
const url = `multi-search`;

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

///
Expand All @@ -243,8 +245,10 @@ class Client {
* @param parameters - Parameters to browse the tasks
* @returns Promise returning all tasks
*/
async getTasks(parameters: TasksQuery = {}): Promise<TasksResults> {
return await this.tasks.getTasks(parameters);
async getTasks(
...params: Parameters<TaskClient["getTasks"]>
): ReturnType<TaskClient["getTasks"]> {
return await this.tasks.getTasks(...params);
}

/**
Expand All @@ -253,8 +257,10 @@ class Client {
* @param taskUid - Task identifier
* @returns Promise returning a task
*/
async getTask(taskUid: number): Promise<Task> {
return await this.tasks.getTask(taskUid);
async getTask(
...params: Parameters<TaskClient["getTask"]>
): ReturnType<TaskClient["getTask"]> {
return await this.tasks.getTask(...params);
}

/**
Expand All @@ -265,13 +271,9 @@ class Client {
* @returns Promise returning an array of tasks
*/
async waitForTasks(
taskUids: number[],
{ timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {},
): Promise<Task[]> {
return await this.tasks.waitForTasks(taskUids, {
timeOutMs,
intervalMs,
});
...params: Parameters<TaskClient["waitForTasks"]>
): ReturnType<TaskClient["waitForTasks"]> {
return await this.tasks.waitForTasks(...params);
}

/**
Expand All @@ -282,13 +284,9 @@ class Client {
* @returns Promise returning an array of tasks
*/
async waitForTask(
taskUid: number,
{ timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {},
): Promise<Task> {
return await this.tasks.waitForTask(taskUid, {
timeOutMs,
intervalMs,
});
...params: Parameters<TaskClient["waitForTask"]>
): ReturnType<TaskClient["waitForTask"]> {
return await this.tasks.waitForTask(...params);
}

/**
Expand All @@ -297,8 +295,10 @@ class Client {
* @param parameters - Parameters to filter the tasks.
* @returns Promise containing an EnqueuedTask
*/
async cancelTasks(parameters: CancelTasksQuery): Promise<EnqueuedTask> {
return await this.tasks.cancelTasks(parameters);
async cancelTasks(
...params: Parameters<TaskClient["cancelTasks"]>
): ReturnType<TaskClient["cancelTasks"]> {
return await this.tasks.cancelTasks(...params);
}

/**
Expand All @@ -307,8 +307,10 @@ class Client {
* @param parameters - Parameters to filter the tasks.
* @returns Promise containing an EnqueuedTask
*/
async deleteTasks(parameters: DeleteTasksQuery = {}): Promise<EnqueuedTask> {
return await this.tasks.deleteTasks(parameters);
async deleteTasks(
...params: Parameters<TaskClient["deleteTasks"]>
): ReturnType<TaskClient["deleteTasks"]> {
return await this.tasks.deleteTasks(...params);
}

///
Expand All @@ -321,9 +323,11 @@ 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`;
const keys = await this.httpRequest.get<KeysResults>(url, parameters);
async getKeys(parameters?: KeysQuery): Promise<KeysResults> {
const keys = (await this.httpRequest.get({
relativeURL: "keys",
params: parameters,
})) as KeysResults;

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

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

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

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

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

/**
Expand All @@ -400,9 +407,8 @@ class Client {
*/
async isHealthy(): Promise<boolean> {
try {
const url = `health`;
await this.httpRequest.get(url);
return true;
const { status } = await this.health();
return status === "available";
} catch {
return false;
}
Expand All @@ -418,8 +424,7 @@ class Client {
* @returns Promise returning object of all the stats
*/
async getStats(): Promise<Stats> {
const url = `stats`;
return await this.httpRequest.get<Stats>(url);
return (await this.httpRequest.get({ relativeURL: "stats" })) as Stats;
}

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

///
Expand All @@ -446,10 +450,10 @@ class Client {
* @returns Promise returning object of the enqueued task
*/
async createDump(): Promise<EnqueuedTask> {
const url = `dumps`;
const task = await this.httpRequest.post<undefined, EnqueuedTaskObject>(
url,
);
const task = (await this.httpRequest.post({
relativeURL: "dumps",
})) as EnqueuedTaskObject;

return new EnqueuedTask(task);
}

Expand All @@ -463,10 +467,9 @@ class Client {
* @returns Promise returning object of the enqueued task
*/
async createSnapshot(): Promise<EnqueuedTask> {
const url = `snapshots`;
const task = await this.httpRequest.post<undefined, EnqueuedTaskObject>(
url,
);
const task = (await this.httpRequest.post({
relativeURL: "snapshots",
})) as EnqueuedTaskObject;

return new EnqueuedTask(task);
}
Expand Down
Loading