chore: Improve typings around model methods (#6324)

This commit is contained in:
Tom Moor
2023-12-28 20:11:27 -04:00
committed by GitHub
parent ed1f345326
commit 55a55376c6
15 changed files with 89 additions and 65 deletions

View File

@@ -2,6 +2,7 @@ import retry from "fetch-retry";
import trim from "lodash/trim";
import queryString from "query-string";
import EDITOR_VERSION from "@shared/editor/version";
import { JSONObject } from "@shared/types";
import stores from "~/stores";
import Logger from "./Logger";
import download from "./download";
@@ -23,11 +24,11 @@ type Options = {
baseUrl?: string;
};
type FetchOptions = {
interface FetchOptions {
download?: boolean;
credentials?: "omit" | "same-origin" | "include";
headers?: Record<string, string>;
};
}
const fetchWithRetry = retry(fetch);
@@ -38,12 +39,12 @@ class ApiClient {
this.baseUrl = options.baseUrl || "/api";
}
fetch = async (
fetch = async <T = any>(
path: string,
method: string,
data: Record<string, any> | FormData | undefined,
data: JSONObject | FormData | undefined,
options: FetchOptions = {}
) => {
): Promise<T> => {
let body: string | FormData | undefined;
let modifiedPath;
let urlToFetch;
@@ -123,9 +124,9 @@ class ApiClient {
response.headers.get("content-disposition") || ""
).split("filename=")[1];
download(blob, trim(fileName, '"'));
return;
return undefined as T;
} else if (success && response.status === 204) {
return;
return undefined as T;
} else if (success) {
return response.json();
}
@@ -133,7 +134,7 @@ class ApiClient {
// Handle 401, log out user
if (response.status === 401) {
await stores.auth.logout(true, false);
return;
throw new AuthorizationError();
}
// Handle failed responses
@@ -168,7 +169,6 @@ class ApiClient {
if (response.status === 403) {
if (error.error === "user_suspended") {
await stores.auth.logout(false, false);
return;
}
throw new AuthorizationError(error.message);
@@ -204,17 +204,17 @@ class ApiClient {
throw err;
};
get = (
get = <T = any>(
path: string,
data: Record<string, any> | undefined,
data: JSONObject | undefined,
options?: FetchOptions
) => this.fetch(path, "GET", data, options);
) => this.fetch<T>(path, "GET", data, options);
post = (
post = <T = any>(
path: string,
data?: Record<string, any> | undefined,
data?: JSONObject | FormData | undefined,
options?: FetchOptions
) => this.fetch(path, "POST", data, options);
) => this.fetch<T>(path, "POST", data, options);
}
export const client = new ApiClient();