From 7aeb9c2cd2f04f0ea7276c59b77a354023553b9f Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 27 Apr 2022 22:45:01 -0700 Subject: [PATCH] chore: cleanup ApiClient --- app/utils/ApiClient.ts | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/app/utils/ApiClient.ts b/app/utils/ApiClient.ts index 7a1a108c2..9e625e58e 100644 --- a/app/utils/ApiClient.ts +++ b/app/utils/ApiClient.ts @@ -1,6 +1,7 @@ import retry from "fetch-retry"; import invariant from "invariant"; -import { map, trim } from "lodash"; +import { trim } from "lodash"; +import queryString from "query-string"; import EDITOR_VERSION from "@shared/editor/version"; import stores from "~/stores"; import isHosted from "~/utils/isHosted"; @@ -20,6 +21,10 @@ type Options = { baseUrl?: string; }; +type FetchOptions = { + download?: boolean; +}; + const fetchWithRetry = retry(fetch); class ApiClient { @@ -33,7 +38,7 @@ class ApiClient { path: string, method: string, data: Record | FormData | undefined, - options: Record = {} + options: FetchOptions = {} ) => { let body: string | FormData | undefined; let modifiedPath; @@ -42,7 +47,7 @@ class ApiClient { if (method === "GET") { if (data) { - modifiedPath = `${path}?${data && this.constructQueryString(data)}`; + modifiedPath = `${path}?${data && queryString.stringify(data)}`; } else { modifiedPath = path; } @@ -69,7 +74,7 @@ class ApiClient { urlToFetch = this.baseUrl + (modifiedPath || path); } - const headerOptions: any = { + const headerOptions: Record = { Accept: "application/json", "cache-control": "no-cache", "x-editor-version": EDITOR_VERSION, @@ -181,13 +186,13 @@ class ApiClient { throw new ServiceUnavailableError(error.message); } - throw new RequestError(error.message); + throw new RequestError(`Error ${error.statusCode}: ${error.message}`); }; get = ( path: string, data: Record | undefined, - options?: Record + options?: FetchOptions ) => { return this.fetch(path, "GET", data, options); }; @@ -195,17 +200,10 @@ class ApiClient { post = ( path: string, data?: Record | undefined, - options?: Record + options?: FetchOptions ) => { return this.fetch(path, "POST", data, options); }; - - private constructQueryString = (data: Record) => { - return map( - data, - (v, k) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}` - ).join("&"); - }; } export const client = new ApiClient();