Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save j-quelly/b8bd61de0775184620df96644952f5c1 to your computer and use it in GitHub Desktop.
Save j-quelly/b8bd61de0775184620df96644952f5c1 to your computer and use it in GitHub Desktop.
/* eslint-disable no-console */
/* eslint-disable no-undef */
window.client = (function() {
function getTimers(success, onError) {
return fetch('/api/timers', {
// tell the server we'll only accept a JSON response
headers: {
Accept: 'application/json',
},
}).then(checkStatus)
.catch(onError)
.then(parseJSON)
.then(success);
}
function createTimer(data, onError) {
return fetch('/api/timers', {
method: 'post',
body: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(checkStatus)
.catch(onError);
}
function updateTimer(data, onError) {
return fetch('/api/timers123', {
method: 'put',
body: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(checkStatus)
.catch(onError);
}
function deleteTimer(data, onError) {
return fetch('/api/timers', {
method: 'delete',
body: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(checkStatus)
.catch(onError);
}
function startTimer(data, onError) {
return fetch('/api/timers/start', {
method: 'post',
body: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(checkStatus)
.catch(onError);
}
function stopTimer(data, onError) {
return fetch('/api/timers/stop', {
method: 'post',
body: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(checkStatus)
.catch(onError);
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
const error = new Error(`HTTP Error ${response.statusText}`);
error.status = response.statusText;
error.response = response;
// console.log(error);
throw error;
}
}
function parseJSON(response) {
return response.json();
}
return {
getTimers,
createTimer,
updateTimer,
startTimer,
stopTimer,
deleteTimer,
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment