Skip to content

Commit

Permalink
Refactor: api requester improvements (#182)
Browse files Browse the repository at this point in the history
* refactor: API Requester

* feat: default user agent
  • Loading branch information
Gorniaky authored Aug 20, 2023
1 parent e79202a commit 66f2b22
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 44 deletions.
6 changes: 4 additions & 2 deletions src/events/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { window } from "vscode";
import extension from "../extension";

extension.on("error", (error) => {
extension.logger.error(`${error.body?.message ?? error}`);
window.showErrorMessage(`${error.body?.message ?? error}`);
const message = error?.body?.message ?? error;

extension.logger.error(message);
window.showErrorMessage(message);
});
4 changes: 2 additions & 2 deletions src/structures/Discloud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,15 @@ class Discloud extends EventEmitter {
try {
await command.run(taskData, ...args);
} catch (error: any) {
logger.error(error);
this.emit("error", error);
this.resetStatusBar();
}
});
} else {
try {
await command.run(taskData, ...args);
} catch (error: any) {
logger.error(error);
this.emit("error", error);
this.resetStatusBar();
}
}
Expand Down
73 changes: 33 additions & 40 deletions src/util/API.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { t } from "@vscode/l10n";
import { discloud } from "discloud.app";
import { decode } from "jsonwebtoken";
import { setTimeout as sleep } from "node:timers/promises";
import { request } from "undici";
import { Dispatcher, request } from "undici";
import { window } from "vscode";
import { RequestOptions } from "../@types";
import extension from "../extension";
import { CPU_ARCH, OS_NAME, OS_PLATFORM, OS_RELEASE, VERSION } from "./constants";
import { DEFAULT_USER_AGENT } from "./constants";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
let { maxUses, time, remain, tokenIsValid } = {
Expand Down Expand Up @@ -46,7 +46,7 @@ export async function requester<T = any>(url: string | URL, config: RequestOptio

url = url.toString();

const processPath = url.split("/").pop()!;
const processPath = `/${url.split("/").slice(4).join("/") ?? url.split("/").at(-1)}`;
const processKey = `${config.method ??= "GET"}.${processPath}`;

if (isVS) {
Expand All @@ -72,62 +72,55 @@ export async function requester<T = any>(url: string | URL, config: RequestOptio
}
}

config.throwOnError = true;
config.headersTimeout = config.headersTimeout ?? 60000;
config.headers = {
...(typeof config.body === "string" ? {
"Content-Type": "application/json",
} : {}),
"api-token": `${extension.token}`,
...(config.headers ?? {}),
"User-Agent": `vscode/${VERSION} (${OS_NAME} ${OS_RELEASE}; ${OS_PLATFORM}; ${CPU_ARCH})`,
};
config.headersTimeout ??= 60000;
Object.assign(config.headers ??= {}, {
"api-token": extension.token,
"User-Agent": DEFAULT_USER_AGENT,
}, typeof config.body === "string" ? {
"Content-Type": "application/json",
} : {});

let response: Dispatcher.ResponseData;
try {
const response = await request(`https://api.discloud.app/v2${url}`, config);

response = await request(`https://api.discloud.app/v2${url}`, config);
} catch {
if (isVS) {
vsProcesses.delete(processKey);
} else {
processes.shift();
}

time = Number(response.headers["ratelimit-reset"]);
initTimer();
maxUses = Number(response.headers["ratelimit-limit"]);
remain = Number(response.headers["ratelimit-remaining"]);

if (!remain)
extension.emit("rateLimited", {
time,
});
throw Error("Missing Connection");
}

return response.body.json() as Promise<T>;
} catch (error: any) {
if (isVS) {
vsProcesses.delete(processKey);
} else {
processes.shift();
}
time = Number(response.headers["ratelimit-reset"]);
initTimer();
maxUses = Number(response.headers["ratelimit-limit"]);
remain = Number(response.headers["ratelimit-remaining"]);

switch (error.code) {
case "DEPTH_ZERO_SELF_SIGNED_CERT":
case "ENOTFOUND":
extension.emit("missingConnection");
throw Error("Missing Connection");
}
if (!remain)
extension.emit("rateLimited", {
time,
});

extension.emit("error", error);
if (isVS) {
vsProcesses.delete(processKey);
} else {
processes.shift();
}

switch (error.statusCode ?? error.status) {
if (response.statusCode > 399) {
switch (response.statusCode) {
case 401:
tokenIsValid = false;
extension.emit("unauthorized");
break;
}

return error;
throw Object.assign(response, { body: await response.body.json() });
}

return response.body.json() as T;
}

export function tokenIsDiscloudJwt(token = extension.token): boolean {
Expand Down
2 changes: 2 additions & 0 deletions src/util/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ export const OS_RELEASE = release().split?.(".").slice(0, 2).join(".") ?? releas
export const OS_PLATFORM = platform();
export const CPU_ARCH = arch();

export const DEFAULT_USER_AGENT = `vscode/${VERSION} (${OS_NAME} ${OS_RELEASE}; ${OS_PLATFORM}; ${CPU_ARCH})`;

export const DISCLOUD_CONFIG_SCOPES = [
"ID",
"TYPE",
Expand Down

0 comments on commit 66f2b22

Please sign in to comment.