Last active
August 18, 2020 18:29
-
-
Save lucianomlima/c8093aafd4a637968b066b2269e63588 to your computer and use it in GitHub Desktop.
Service API example using apisauce for React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable no-console, no-param-reassign */ | |
import { create } from 'apisauce'; | |
import qs from 'qs'; | |
import R from 'ramda'; | |
import config from '../../config'; | |
const api = create({ | |
baseURL: config.baseURL, | |
headers: { | |
Accept: 'application/json', | |
'Cache-Control': 'no-cache' | |
}, | |
timeout: 30000 | |
}); | |
const monitor = (response) => { | |
const { config: { method, url }, data, status } = response; | |
console.group(`Requesting [${method.toUpperCase()}] ${url}:`); | |
console.log('Response Status:', status); | |
console.log('Response Data:', data); | |
console.groupEnd(); | |
}; | |
api.addMonitor(monitor); | |
api.addRequestTransform((request) => { | |
if (R.contains(request.method, ['delete', 'post', 'put'])) { | |
if (!(request.data instanceof FormData)) { | |
request.headers['Content-Type'] = 'application/x-www-form-urlencoded'; | |
request.data = qs.stringify(request.data); | |
} | |
} | |
}); | |
api.addResponseTransform((response) => { | |
if (response.data.erro !== undefined) { | |
response.ok = false; | |
let message = (typeof response.data.erro === 'object') | |
? response.data.erro.mensagem | |
: response.data.erro; | |
if (!message) { | |
message = 'Erro desconhecido'; | |
} | |
response.data = { message }; | |
} else { | |
const data = response.data.item || response.data.itens || null; | |
if (response.data['access-token'] !== undefined) { | |
data.tokenapi = response.data['access-token']; | |
} | |
if (response.data.total_itens !== undefined) { | |
response.count = +response.data.total_itens; | |
} | |
response.data = data; | |
} | |
}); | |
export default api; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment