Files
COMP-2707-final-project/frontend/src/utils.ts

54 lines
1.3 KiB
TypeScript

const { REACT_APP_BACKEND_URL } = process.env;
const makeRequest = ({ endpoint, method, body = null }): Promise<Response> => {
const req: RequestInit = {
method: method,
credentials: "include",
headers: { "content-type": "application/json" },
mode: "cors",
};
if (body) {
req["body"] = JSON.stringify(body);
}
return fetch(`${REACT_APP_BACKEND_URL}/${endpoint}`, req);
};
const sendLoginRequest = async (
username: string,
password: string
): Promise<object> => {
const p: Promise<object> = new Promise(async (res) => {
await makeRequest({
endpoint: "login",
method: "POST",
body: { username, password },
})
.then((resp) => resp.json())
.then((data) => {
if (data.error) {
res({ isError: true, ...data });
}
res({ isError: false, ...data });
});
res({ isError: true });
});
return p;
};
const sendLogoutRequest = async (): Promise<object> => {
const p: Promise<object> = new Promise(async (res) => {
await makeRequest({
endpoint: "logout",
method: "POST",
})
.then((resp) => resp.json())
.then((data) => {
res({ isError: false, ...data });
});
res({ isError: true });
});
return p;
};
export { makeRequest, sendLoginRequest, sendLogoutRequest };