Continue to modernize the async calls by refactoring Fetch API into beststudynotes.com. This time, work on POST [1, 2, 3].
let reqHeader = new Headers();
reqHeader.append('Content-Type', 'application/json; charset=utf-8');
reqHeader.append('Authorization', myIdToken);
We set up the headers here with content type and authorization.
let initObject = {
method: 'POST',
headers: reqHeader,
body: JSON.stringify(input)
};
Then we initialize an options object containing any custom settings.
let userRequest = new Request(url, initObject);
We create a request object with url and init object.
fetch(userRequest)
.then(validateResponse)
.then(validateContentTypeIsJSON)
.then(readResponseAsJSON)
.then(success)
.catch(fail);
We call Fetch, use chain actions to validate response, extract the JSON, and work on the data. If successful, ‘success’ is called. Otherwise, the ‘fail’ is called.
Please note that success in Fetch API is different from JQuery [2].
“The Promise returned from fetch()
won’t reject on HTTP error status even if the response is an HTTP 404
or 500
. Instead, it will resolve normally (with ok
status set to false
), and it will only reject on network failure or if anything prevented the request from completing.”
The pseudo-code of functions below.
function validateResponse(response) {
if (!response.ok) {
throw Error(response.status);
}
return response;
}
function validateContentTypeIsJSON(response) {
const contentType = response.headers.get('content-type');
if (!contentType ||
!contentType.includes('application/json')) {
throw new TypeError("JSON is expected!");
}
return response;
}
function readResponseAsJSON(response) {
return response.json();
}
function success(jsonResponse) {
// process the response
}
function fail(error) {
// process the error
}
References:
2. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
3. https://developer.mozilla.org/en-US/docs/Web/API/Request/Request