58 lines
1.4 KiB
JavaScript
58 lines
1.4 KiB
JavaScript
class ApiService {
|
|
|
|
getQuestions(userId, onSuccess, onError) {
|
|
this._get('/api/questions' + userId, onSuccess, onError);
|
|
};
|
|
|
|
_get(url, onSuccess, onError) {
|
|
fetch(url)
|
|
.then(this._handleResponse(onSuccess, onError))
|
|
.catch((error) => {
|
|
onError({ error: error.message });
|
|
});
|
|
};
|
|
|
|
_post(url, requestData, onSuccess, onError) {
|
|
fetch(url, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify(requestData)
|
|
})
|
|
.then(this._handleResponse(onSuccess, onError))
|
|
.catch((error) => {
|
|
onError(error);
|
|
});
|
|
};
|
|
|
|
_put(url, requestData, onSuccess, onError) {
|
|
fetch(url, {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify(requestData)
|
|
}).then(this._handleResponse(onSuccess, onError))
|
|
.catch((error) => {
|
|
onError(error);
|
|
})
|
|
};
|
|
|
|
_handleResponse = (onSuccess, onError) => (response) => {
|
|
if (response.status === 200) {
|
|
response.json()
|
|
.then(onSuccess)
|
|
} else if (response.status === 400) {
|
|
// JSON Syntax error
|
|
response.json().then(onError)
|
|
}
|
|
else {
|
|
onError({ "message": "Backend returned status: " + response.status })
|
|
}
|
|
};
|
|
}
|
|
|
|
export default ApiService;
|