Skip to content

Instantly share code, notes, and snippets.

@jalispran
Created July 30, 2020 04:18
Show Gist options
  • Save jalispran/1a160f050cb3ae410f41a89188d1ec18 to your computer and use it in GitHub Desktop.
Save jalispran/1a160f050cb3ae410f41a89188d1ec18 to your computer and use it in GitHub Desktop.
export const post = (url, body, successCallback, failureCallback) => {
let requestOptions = {
method: 'POST',
body: body,
};
call(url, requestOptions, successCallback, failureCallback);
};
export const get = (url, successCallback, failureCallback) => {
let requestOptions = {
method: 'GET',
};
call(url, requestOptions, successCallback, failureCallback);
};
async function call(url, requestOptions, successCallback, failureCallback) {
addHeaders(requestOptions);
await modifyBody(requestOptions);
requestOptions.redirect = 'follow';
console.debug('data: ', requestOptions.body);
console.debug('url: ', url);
fetch(url, requestOptions)
.then(response => {
console.debug(response);
return response.json();
})
.then(result => successCallback(result))
.catch(error => failureCallback(error));
}
function addHeaders(requestOptions) {
let myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
requestOptions.headers = myHeaders;
}
async function modifyBody(requestOptions) {
let {body} = requestOptions;
if (!body) {
return;
}
let {data} = body;
if (!data) {
return;
}
data.apiversion = '<api-version-here>';
data.secret = '<api-secret-here>';
requestOptions.body = JSON.stringify(body);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment