From 1010a102f88eca8fd15e13f3e537499307589851 Mon Sep 17 00:00:00 2001 From: Ken Eucker Date: Sun, 2 Jan 2022 17:15:29 -0800 Subject: [PATCH] fix(utils): resolves issues with the response of errored requests --- example/index.js | 1 + src/common/utils.ts | 37 +++++++++++++++++++++++++++---------- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/example/index.js b/example/index.js index 3fd52bd4..2ac08245 100644 --- a/example/index.js +++ b/example/index.js @@ -11,6 +11,7 @@ const imgur = new ImgurClient({ accessToken: process.env.ACCESS_TOKEN, clientSecret: process.env.CLIENT_SECRET, clientId: process.env.CLIENT_ID, + rapidApiKey: process.env.RAPID_API_KEY, }); const run = async (client) => { diff --git a/src/common/utils.ts b/src/common/utils.ts index abc0e7e5..b700477e 100644 --- a/src/common/utils.ts +++ b/src/common/utils.ts @@ -33,29 +33,46 @@ export function createForm(payload: string | Payload): FormData { } export function getImgurApiResponseFromResponse( - response: AxiosResponse | string + response: AxiosResponse ): ImgurApiResponse { let success = true; let data; let status = 200; + const responseIsValid = + response && + (typeof response.status !== 'undefined' || + typeof response.data?.status !== 'undefined') && + typeof response.data !== 'undefined'; + const responseIsSuccess = responseIsValid && !!response.data.success; + const responseIsError = + responseIsValid && + !responseIsSuccess && + (typeof response.data.data?.error !== 'undefined' || + typeof response.data.errors !== 'undefined'); + + const getResponseData = (d) => + Array.isArray(d) ? d.map((t) => (responseIsError ? t.detail : t.data)) : d; if (typeof response === 'string') { data = response as string; status = 500; success = false; - } else if ( - !!response && - typeof response?.data?.status !== 'undefined' && - typeof response?.data?.success !== 'undefined' - ) { + } else if (responseIsSuccess) { success = response.data.success; status = response.data.status; - data = response.data.data?.error - ? response.data.data?.error + data = response.data.data.error + ? response.data.data.error : response.data.data; } else { - status = response ? response.status : status; - data = response ? response.data : data; + status = + response.data.data?.error?.code ?? + response.status ?? + response.data.status; + data = getResponseData( + responseIsError + ? response.data.errors ?? response.data.data.error.message + : response.data.data ?? response.data + ); } return {