diff --git a/composables/useApiClient.ts b/composables/useApiClient.ts index de15816..12ba8f1 100644 --- a/composables/useApiClient.ts +++ b/composables/useApiClient.ts @@ -24,20 +24,7 @@ const useApiClient = () => { `${nuxtConfig.public.baseURL}${url}?${new URLSearchParams(params)}`, { headers } ) - .then((resp: any) => { - if (resp.ok) - return { - data: resp.json(), - unauthorized: false, - error: null - } as BackendResponse - if (resp.status === 401) { - authStore.clearToken() - authStore.clearUser() - return { data: null, unauthorized: true, error: resp.status } - } - return { data: null, unauthorized: false, error: resp.statusText } - }) + .then((resp: Response) => handleResponse(resp)) .catch((e: any) => { return { data: null, unauthorized: false, error: e } as BackendResponse }) @@ -55,31 +42,40 @@ const useApiClient = () => { headers, body }) - .then((resp: any) => { - if (resp.ok) { - let d - try { - d = resp.json() - } catch (e) { - d = null - } - return { - data: d, - unauthorized: false, - error: null - } as BackendResponse - } - if (resp.status === 401) { - authStore.clearToken() - authStore.clearUser() - return { data: null, unauthorized: true, error: resp.status } - } - return { data: null, unauthorized: true, error: resp.statusText } - }) + .then((resp: any) => handleResponse(resp)) .catch((e: any) => { return { data: null, unauthorized: false, error: e } as BackendResponse }) } + + const handleResponse = async (resp: Response): Promise => { + if (resp.ok) { + const respStr = await resp.text() + let respData + try { + respData = JSON.parse(respStr) + } catch (e) {} + return { + data: respData, + unauthorized: false, + error: null + } as BackendResponse + } + if (resp.status === 401) { + authStore.clearToken() + authStore.clearUser() + return { + data: null, + unauthorized: true, + error: resp.status + } as BackendResponse + } + return { + data: null, + unauthorized: true, + error: resp.statusText + } as BackendResponse + } return { get, post } }