parsing headers
This commit is contained in:
parent
976698e4b8
commit
1d4a183a3e
@ -16,23 +16,41 @@ export const setSession = (user) => {
|
|||||||
sessionStorage.setItem('user', JSON.stringify(user));
|
sessionStorage.setItem('user', JSON.stringify(user));
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fetchUser = async () => {
|
export const fetchUser = async (force = false) => {
|
||||||
|
const user = getUser();
|
||||||
|
if (!force && user) return user;
|
||||||
|
|
||||||
const result = await fetch('/api/user');
|
const result = await fetch('/api/user');
|
||||||
if (result.status === 200) {
|
if (result.status === 200) {
|
||||||
const data = await result.json();
|
const data = await result.json();
|
||||||
setSession(data);
|
setSession(data);
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const post = (url, body) => {
|
const parseResponse = async (response) => {
|
||||||
return fetch(url, {
|
const { headers: rawHeaders, status } = response;
|
||||||
|
const headers = [...rawHeaders].reduce((acc, [key, val]) => {
|
||||||
|
acc[key.toLowerCase()] = val;
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
const success = status >= 200 && status < 400;
|
||||||
|
const base = { success, status };
|
||||||
|
if (headers['content-type']?.includes('application/json')) {
|
||||||
|
const data = await response.json();
|
||||||
|
return {...base, ...data};
|
||||||
|
}
|
||||||
|
return { ...base, message: await response.text() };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const post = async (url, body) => {
|
||||||
|
const response = await fetch(url, {
|
||||||
method: 'post',
|
method: 'post',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
body: JSON.stringify(body)
|
body: JSON.stringify(body)
|
||||||
});
|
});
|
||||||
|
return parseResponse(response);
|
||||||
|
|
||||||
};
|
};
|
Loading…
Reference in New Issue
Block a user