-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread.js
409 lines (366 loc) · 11 KB
/
read.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//Login Modal
const loginModal = document.getElementById("login-modal");
const loginForm = document.getElementById("login-form");
const email = document.getElementById("email");
const password = document.getElementById("password");
const signupSuccessDiv = document.getElementById("signup-success");
let numOfLikes;
let token;
let user;
let id;
let userEmail;
// for Blog and comments
let submitComment = document.getElementById("submit-comment-form");
let userComment = document.getElementById("comment");
//for liking
const likeBtn = document.querySelector(".like-button");
const likeBtnStatus = document.getElementById("status");
const showNumOfLikes = document.getElementById("show-num-likes");
console.log(likeBtnStatus);
const showStatus = (text) => {
likeBtnStatus.style.display = "block";
likeBtnStatus.innerHTML = text;
};
userComment.disabled = true;
let urlParams = new URLSearchParams(window.location.search);
let idFromUrl = urlParams.get("id");
let date = document.getElementsByClassName("date");
let title = document.getElementsByClassName("title");
let content = document.getElementsByClassName("content");
let author = document.getElementsByClassName("author-display");
const signP = document.getElementById("p");
const submitCommentBtn = document.getElementById("for-submit-comment-btn");
//for nav Login and signout
const loginBtn = document.querySelector("p.login");
const logoutBtn = document.querySelector("p.logout");
//signout logic
const signOut = () => {
localStorage.removeItem("token");
window.location = "./login.html";
};
//Regarding user and token
if (localStorage.getItem("token")) {
//if user signed in
console.log(localStorage.getItem("token"));
token = localStorage.getItem("token");
const decodedToken = JSON.parse(atob(token.split(".")[1]));
user = decodedToken.name;
id = decodedToken.userId.toString();
userEmail = decodedToken.email;
userComment.disabled = false;
submitCommentBtn.style.display = "block";
signP.style.display = "none";
//show logout btn
logoutBtn.style.display = "block";
} else {
//if user not signed in
console.log(userComment);
userComment.disabled = true;
signP.style.display = "block";
submitCommentBtn.style.display = "none";
loginBtn.style.display = "block";
}
const openLoginModal = () => {
loginModal.style.display = "block";
};
const reset = () => {
email.value = "";
password.value = "";
signupSuccessDiv.style.display = "none";
};
const closeLoginModal = () => {
loginModal.style.display = "none";
reset();
};
window.addEventListener("click", (e) => {
if (e.target == loginModal) {
closeLoginModal();
}
});
const resetField = (arg1, arg2) => {
arg1.value = "";
arg2.value = "";
};
const signupMessage = (arg, text, color) => {
arg.style.display = "block";
arg.style.backgroundColor = color;
arg.innerHTML = text;
};
const redirect = (time, path) => {
setTimeout(function () {
window.location = path;
}, time);
};
const reload = () => {
setTimeout(function () {
closeLoginModal();
location.reload();
}, 2000);
};
let obj = {
name: null,
password: null,
};
const setError = (element, message) => {
const field = element.parentElement;
const errorField = field.querySelector(".error");
errorField.innerHTML = message;
errorField.style.marginTop = "5px";
field.classList.add("error");
field.classList.remove("success");
};
const setSuccess = (element) => {
const field = element.parentElement;
const errorField = field.querySelector(".error");
errorField.innerText = "";
field.classList.remove("error");
field.classList.add("success");
};
const isValidEmail = (arg) => {
const regExp =
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return regExp.test(arg);
};
const checkTruthy = (arg) => {
for (let key in arg) {
if (!arg[key]) {
return false;
}
}
return true;
};
const validateInputs = () => {
let emailText = email.value.trim();
let passwordText = password.value.trim();
//validate email
if (emailText === "") {
setError(email, "Please enter your email");
obj.name = false;
} else if (isValidEmail(emailText) === false) {
setError(email, "Invalid email");
obj.name = false;
} else {
setSuccess(email);
obj.name = true;
}
//validate password
if (passwordText === "") {
setError(password, "Please enter your password");
obj.password = false;
} else {
setSuccess(password);
obj.password = true;
}
};
loginForm.addEventListener("submit", (e) => {
e.preventDefault();
validateInputs();
if (checkTruthy(obj) === true) {
const loginEndpoint = "https://my-brand-atlp-be.onrender.com/api/login";
const userData = {
email: email.value,
password: password.value,
};
const fetchOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
};
const startLogin = async () => {
try {
signupMessage(signupSuccessDiv, "... processing", "#0b5ed7");
const response = await fetch(loginEndpoint, fetchOptions);
if (!response.ok) {
if (response.status === 401) {
signupMessage(signupSuccessDiv, "Wrong credentials", "#bb2d3b");
resetField(email, password);
} else if (response.status === 404) {
signupMessage(signupSuccessDiv, "User not found", "#bb2d3b");
resetField(email, password);
} else {
signupMessage(
signupSuccessDiv,
"Check credentials format",
"#bb2d3b"
);
resetField(email, password);
}
throw new Error("Something went wrong");
}
signupMessage(signupSuccessDiv, "Success", "#198754");
const data = await response.json();
token = data.token;
localStorage.setItem("token", token);
const decodedToken = JSON.parse(atob(token.split(".")[1]));
signP.style.display = "none";
console.log(decodedToken.role);
reload();
} catch (e) {
console.log(`Something went wrong: ${e}`);
}
};
startLogin();
}
});
//for rendering comments
let commentSection = document.getElementsByClassName("list-comments");
//Date formater
const formatDate = (arg) => {
const date = new Date(arg);
const options = { year: "numeric", month: "long", day: "numeric" };
const formattedDate = date.toLocaleDateString("en-US", options);
return formattedDate;
};
//render comments
const renderComments = (arg) => {
const commentData = arg.comments;
if (commentData.length === 0) {
commentSection[0].innerHTML += `<p class="no-comment">No Comments to show </p>`;
} else {
commentSection[0].innerHTML = `<div class="comment-title">
<h1>All comments</h1>
</div>`;
commentData.forEach((item) => {
commentSection[0].innerHTML += `
<div class="listed">
<div class="avatar-comment">
<i class="fa-solid fa-circle-user"></i>
</div>
<div class="content-comment">
<div class="comment-head">
<p>${item.name}</p>
<p>${formatDate(item.timestamp)}</p>
</div>
<p>${item.content}</p>
<!-- <div class="comment-foot">
<i class="fa-solid fa-thumbs-up"></i>
<i class="fa-solid fa-thumbs-down"></i>
<i class="fa-solid fa-heart"></i>
</div> -->
</div>
</div>
`;
});
}
};
document.addEventListener("DOMContentLoaded", async () => {
// For Page Display
try {
content[0].innerHTML = `<p class="loading">Loading...<p>`;
const response = await fetch(
`https://my-brand-atlp-be.onrender.com/api/blogs/${idFromUrl}`
);
if (!response.ok) {
throw new Error("Network response was not ok");
} else {
content[0].innerHTML = "";
const blogData = await response.json();
const data = blogData.data;
date[0].innerHTML = formatDate(data.createdAt);
title[0].innerHTML = data.title;
content[0].innerHTML = data.content;
const likes = data.likes;
numOfLikes = likes.length;
showNumOfLikes.innerHTML = numOfLikes;
console.log(numOfLikes);
author[0].innerHTML = data.author;
renderComments(data);
}
} catch (error) {
console.error("Error fetching blog:", error);
content[0].innerHTML = `<p class="loading">Loading...<p>`;
}
});
submitComment.addEventListener("submit", (e) => {
e.preventDefault();
const addCommentData = {
name: user,
email: "[email protected]",
content: userComment.value.trim(),
};
const addCommentEndpoint = `https://my-brand-atlp-be.onrender.com/api/comments/${idFromUrl}`;
const fetchOptions = {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(addCommentData),
};
const addComment = async () => {
try {
const response = await fetch(addCommentEndpoint, fetchOptions);
const jsonResponse = await response.json();
if (!response.ok) {
} else {
location.reload();
}
} catch (e) {
console.log(e);
}
};
addComment();
});
if (token == null) {
likeBtn.addEventListener("click", () => {
showStatus("you need to login first!");
setTimeout(() => {
likeBtnStatus.style.display = "none";
}, 3000);
});
} else {
let likeData = {
userId: id,
name: user,
email: userEmail,
};
console.log(likeData);
const likeEndpoint = `https://my-brand-atlp-be.onrender.com/api/likes/${idFromUrl}`;
const likeEndpointOptions = {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(likeData),
};
const likeBlog = async () => {
try {
console.log("liking");
showStatus("liking...");
const response = await fetch(likeEndpoint, likeEndpointOptions);
const jsonResponse = await response.json();
console.log(response);
if (!response.ok) {
if (response.status == "404") {
showStatus("blog not found");
console.log("can't find blog");
} else if (response.status == "400") {
console.log("can't comment twice");
showStatus("You can only like a blog one time");
setTimeout(() => {
likeBtnStatus.style.display = "none";
}, 3000);
} else {
console.log("code: " + response.status);
console.log("Error");
}
} else {
console.log("Liked");
showStatus("Thank you!");
setTimeout(() => {
location.reload();
}, 3000);
console.log(jsonResponse.data.likes);
}
} catch (e) {
console.error(e);
}
};
likeBtn.addEventListener("click", () => {
console.log("attempt liking");
likeBlog();
});
}