-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccount.js
52 lines (42 loc) · 1.22 KB
/
account.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const API_URL = "https://hotello.dev-space.top";
const deleteFormRef = document.getElementById("delete-form");
const fetchUser = async ({ email, password }) => {
const response = await fetch(`${API_URL}/sign-in`, {
method: "POST",
body: JSON.stringify({ email: email.value, password: password.value }),
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const { data } = await response.json();
return data;
};
const deleteUser = async (token) => {
const response = await fetch(`${API_URL}/profile`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
};
const onDeleteFormSubmit = async (event) => {
event.preventDefault();
const { email, password } = event.target.elements;
if (!email.value || !password.value) {
return;
}
try {
const user = await fetchUser({ email, password });
await deleteUser(user.token);
} catch (error) {
console.log(error.message);
}
};
deleteFormRef.addEventListener("submit", onDeleteFormSubmit);