Skip to content

Commit

Permalink
♻️ (composables/useApiClient) response handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Shion1305 committed May 5, 2024
1 parent 81041bb commit f8b9b5c
Showing 1 changed file with 31 additions and 35 deletions.
66 changes: 31 additions & 35 deletions composables/useApiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
Expand All @@ -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<BackendResponse> => {
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 }
}

Expand Down

0 comments on commit f8b9b5c

Please sign in to comment.