ZPRP_Rental/react-go/src/_services/article.service.js

78 lines
1.9 KiB
JavaScript

import { authHeader } from '../_helpers';
import config from 'config';
export const articleService = {
addArticle,
getAll,
getById,
update,
delete: _delete
};
function addArticle(article) {
const requestOptions = {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(article)
};
console.log(article)
return fetch(`${config.apiUrl}article`, requestOptions).then(handleResponse);
}
function getAll() {
const requestOptions = {
method: 'GET',
credentials: 'include',
headers: authHeader()
};
return fetch(`${config.apiUrl}/articles`, requestOptions).then(handleResponse);
}
function getById(id) {
const requestOptions = {
method: 'GET',
credentials: 'include',
headers: authHeader()
};
return fetch(`${config.apiUrl}/users/${id}`, requestOptions).then(handleResponse);
}
function update(user) {
const requestOptions = {
method: 'PUT',
credentials: 'include',
headers: { ...authHeader(), 'Content-Type': 'application/json' },
body: JSON.stringify(user)
};
return fetch(`${config.apiUrl}/users/${user.id}`, requestOptions).then(handleResponse);;
}
function _delete(id) {
const requestOptions = {
method: 'DELETE',
credentials: 'include',
headers: authHeader()
};
return fetch(`${config.apiUrl}/users/${id}`, requestOptions).then(handleResponse);
}
function handleResponse(response) {
return response.text().then(text => {
const data = text && JSON.parse(text);
if (!response.ok) {
if (response.status === 401) {
logout();
location.reload(true);
}
const error = (data && data.message) || response.statusText;
return Promise.reject(error);
}
return data;
});
}