Skip to content

Commit

Permalink
fix(utils): resolves issues with the response of errored requests
Browse files Browse the repository at this point in the history
  • Loading branch information
KenEucker committed Jan 3, 2022
1 parent a48baa7 commit 1010a10
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
1 change: 1 addition & 0 deletions example/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
37 changes: 27 additions & 10 deletions src/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 1010a10

Please sign in to comment.