Created
May 24, 2017 22:15
-
-
Save hontas/df2b9c2e6b04dd4f62c42266c0ce0c92 to your computer and use it in GitHub Desktop.
fetch handler
This file contains 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
const NO_CONTENT = 204; | |
const getHeaders = { | |
'accept': 'application/json' | |
}; | |
const postHeaders = { | |
'Content-Type': 'application/json' | |
}; | |
export function getJSON(url) { | |
return fetch(url, { headers: getHeaders }) | |
.then(handleResponse); | |
} | |
export function postJSON(url, content) { | |
return fetch(url, { | |
headers: postHeaders, | |
credentials: 'include', | |
method: 'POST', | |
body: JSON.stringify(content) | |
}); | |
} | |
function handleResponse(response) { | |
const contentType = response.headers.get('Content-Type'); | |
const { status, statusText } = response; | |
if (contentType === 'application/json') { | |
return response.json() | |
.then(json => { | |
if (response.ok) { | |
return json; | |
} else { | |
return Promise.reject(Object.assign({}, json, { status, statusText })); | |
} | |
}); | |
} | |
if (contentType === 'text/html') { | |
return response.text(); | |
} | |
console.log(`Content-Type: '${contentType}' not supported - returning response.`); | |
return Promise.resolve(response); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment