Skip to content

Instantly share code, notes, and snippets.

@zeing
Last active July 1, 2021 13:34
Show Gist options
  • Select an option

  • Save zeing/4eb6094bf67d9690fa10d2ad3163ca78 to your computer and use it in GitHub Desktop.

Select an option

Save zeing/4eb6094bf67d9690fa10d2ad3163ca78 to your computer and use it in GitHub Desktop.
API
import api from 'api.js'
function MyApp({ Component, pageProps, router: { route } }) {
const naviMonitor = (response) => {
console.log('monitor', response)
if (!response.ok) {
const error = new Error(response.data?.message)
error.status = response.data?.code
error.response = response
throw error
}
if (response.status === 401) {
console.warn('Unhandled session expiration')
signOut()
}
if (response.problem === 'NETWORK_ERROR') {
console.warn('Unhandled request without connection')
}
if (response.ok && [604, 605].includes(response.data.code)) {
console.warn('604, 605')
signOut()
}
}
api.addMonitor(naviMonitor)
return (
<Component {...pageProps} />
)
}
export default MyApp
import { create } from 'apisauce'
// console.log('process.env.NEXT_PUBLIC_API_URL', process.env.NEXT_PUBLIC_API_URL)
// define the api
const api = create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: {},
})
api.addResponseTransform((response) => {
// if (response.status >= 400 || !response.ok) {
// const error = new Error(
// response.data?.message || response.originalError.message || response.problem,
// )
// error.status = response.status
// error.response = response
// // throw error
// }
// if (response.ok && response.data.code === 0) {
// // just mutate the data to what you want.
// response.data = response.data.data
// } else {
// const error = new Error(response.data?.message)
// error.status = response.data?.code
// error.response = response
// throw error
// }
if (response.ok) {
if (response.data.code === 0) response.data = response.data.data
else {
response.ok = false
response.problem = response.data?.message
response.message = response.data?.message
response.status = response.data?.code
}
} else {
response.problem =
response.data?.message ||
response.originalError.message ||
response.problem
response.message =
response.data?.message ||
response.originalError.message ||
response.problem
response.status = response.data?.code || response.status
}
})
export default api
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment