Last active
November 1, 2018 08:40
-
-
Save andreasvirkus/9526ebbe608d39a29d7d5e100c37b0d3 to your computer and use it in GitHub Desktop.
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
/** Small module to expose get and post methods around fetch for API communication (bearer token in headers, etc.) */ | |
const host = process.env.API_DOMAIN | |
const prefix = `/api/v1` | |
export const getData = ({ url, accessToken, paymentId, headers, noJson }) => | |
request({ url, accessToken, paymentId, headers, noJson, method: 'GET' }) | |
export const postData = ({ url, accessToken, paymentId, headers, data, method }) => { | |
method = method || 'POST' | |
return request({ url, accessToken, paymentId, headers, data, method }) | |
} | |
const request = async ({ url, data, method, accessToken, paymentId, headers, noJson }) => { | |
const baseHeaders = { | |
Authorization: `Bearer ${accessToken}`, | |
'Content-Type': 'application/json; charset=utf-8' | |
} | |
const requestOptions = { | |
method, | |
headers: Object.assign(baseHeaders, headers), | |
mode: 'cors', | |
cache: 'no-cache' | |
} | |
if (!['DELETE', 'GET'].includes(method)) { | |
requestOptions.body = JSON.stringify(data) | |
} | |
console.log(`API:: Making a ${method} request to ${url} with headers:`, | |
headers, ` and body::`, data) | |
const response = await fetch(`${host}${prefix}${url}`, requestOptions) | |
if (response.ok) return noJson ? response.text() : response.json() | |
const errJson = await response.json() | |
console.error('API:: Request ERR (json):', errJson) | |
if (response.status === 401) { | |
console.error('API:: Session expired', response.status) | |
} else if (response.status === 400) { | |
console.error('API:: Bad request performed') | |
} | |
throw new Error(response) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment