Skip to content

Commit b355132

Browse files
committed
user creation is applied according to what was taught in classes
1 parent 3246eb6 commit b355132

File tree

10 files changed

+220
-29
lines changed

10 files changed

+220
-29
lines changed

src/js/main.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,8 @@ document.addEventListener("DOMContentLoaded", () => {
3030
})
3131
container.addEventListener('load-posts-finished', () => {
3232
hide();
33-
showNotification('Posts Loaded' , 'success') // <-- Here we add type as “success”.
3433
})
35-
container.addEventListener('load-tweets-error', (event) => {
34+
container.addEventListener('load-posts-error', (event) => {
3635
const errorMessage = event.detail; // <-- Here we are passing the error obtained from "showPostsController.js".
3736
showNotification(errorMessage) // <-- Here we do not add the type “success” so it will be “error”.
3837
})
File renamed without changes.

src/js/modules/login/loginModel.js

Whitespace-only changes.

src/js/modules/show-posts/showPostsController.js

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@ import { getPosts } from "./showPostsModel.js"
22
import { buildPost } from './showPostsView.js';
33

44
export async function showPostsController(container) { // the container is ".posts-container"
5-
5+
66
try {
77

8-
container.dispatchEvent(new CustomEvent("load-posts-started"))
9-
/* const event = new CustomEvent("load-posts-started");
10-
container.dispatchEvent(event); */
8+
9+
//container.dispatchEvent(new CustomEvent("load-posts-started"))
10+
const event = new CustomEvent("load-posts-started");
11+
container.dispatchEvent(event); // --> This "event" goes to "load-posts-started".
1112

1213
const posts = await getPosts();
1314
drawPosts(posts, container)
@@ -22,15 +23,13 @@ export async function showPostsController(container) { // the container is ".pos
2223

2324
// By sending the following line "main.js" will listen for this event and do what we told it to do,
2425
// in this case "showNotification(errorMesage)" method.
25-
container.dispatchEvent(event)
26-
27-
alert(error.message) // this error comes from showPostsModel.js.
26+
container.dispatchEvent(event) // --> This "event" goes to "load-posts-error".
2827

2928
} finally {
3029

31-
container.dispatchEvent(new CustomEvent("load-posts-finished"))
32-
/* const event = new CustomEvent("load-posts-finished")
33-
container.dispatchEvent(event) */
30+
//container.dispatchEvent(new CustomEvent("load-posts-finished"))
31+
const event = new CustomEvent("load-posts-finished")
32+
container.dispatchEvent(event) // --> This "event" goes to "load-posts-finished".
3433

3534
}
3635
}
@@ -40,7 +39,7 @@ function drawPosts(posts, container) {
4039
container.innerHTML = ''; // I clean all displayed posts if any.
4140

4241
if (posts.length === 0) {
43-
alert("Sorry, no posts available!")
42+
//alert("Sorry, no posts available!")
4443
} else { // I add this "else" to have more clarity of the code.
4544

4645
posts.forEach((post) => { // If "posts" is an empty array, the "forEach" will not be executed.
Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,23 @@
11
export async function getPosts() {
22

3-
let posts = [];
4-
5-
try {
6-
const response = await fetch('http://localhost:8000/api/posts')
7-
posts = await response.json();
8-
// This code line won't be executed if fech fails.
9-
// Automatically catch(error) will be executed.
10-
} catch (error) {
11-
/* being in the model if an error occurs on fech,
12-
the error will have a better context so you have a better answer for detecting problems with BD. */
3+
let posts = [];
134

14-
// here "error" would return a 'status code'.
15-
16-
throw new Error("It was not possible to get the posts. Please try again later.") // this error is sended to showPostsController.js
5+
try {
6+
const response = await fetch('http://localhost:8000/api/posts')
7+
8+
if (!response.ok) {
9+
// It will occur when there is a connection to the server and to the database, but the server responds with an error.
10+
throw new Error("Server error: " + response.status + " - " + response.statusText);
1711
}
18-
19-
return posts;
20-
}
12+
13+
posts = await response.json();
14+
15+
} catch (error) {
16+
17+
// It will occur when you cannot connect to the server or database at all.
18+
console.error("Fetch error:", error);
19+
throw new Error("It was not possible to get the posts. Please try again later.");
20+
}
21+
22+
return posts;
23+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import { REGEXP } from "../../utils/constants.js";
2+
import { createUser } from "../signup/signUpModel.js";
3+
4+
export const signUpController = (form) => {
5+
6+
form.addEventListener("submit", (event) => {
7+
8+
/* By default, when a form is submitted the browser reloads the page and
9+
all JavaScript and current app state information is lost. */
10+
event.preventDefault();
11+
12+
const nameElement = form.querySelector('#name');
13+
const name = nameElement.value;
14+
15+
const emailElement = form.querySelector('#email');
16+
const email = emailElement.value;
17+
18+
const passwordElement = form.querySelector('#password');
19+
const password = passwordElement.value;
20+
21+
const passwordConfirmElement = form.querySelector('#password-confirm');
22+
const passwordConfirm = passwordConfirmElement.value;
23+
24+
const errors = []
25+
26+
// validate email format
27+
const emailRegExp = REGEXP.mail;
28+
29+
/* ".test(email)" is a method of regular expressions in JavaScript.
30+
It returns "true" if the email matches the pattern and "false" if it does not. */
31+
32+
/* Regular expressions (or regex) are patterns used to search, validate or replace text. */
33+
34+
/* ".test()" is a JavaScript method used with regular expressions to check if a text conforms to a pattern. */
35+
if (!emailRegExp.test(email)) {
36+
errors.push('The email format is incorrect.')
37+
}
38+
39+
// check that the passwords are the same
40+
if (password !== passwordConfirm) {
41+
errors.push('Passwords are not the same.')
42+
}
43+
44+
if (errors.length === 0) {
45+
handleCreateUser(name, email, password, form)
46+
} else {
47+
errors.forEach(error => {
48+
const event = new CustomEvent("register-error", {
49+
detail: error
50+
});
51+
form.dispatchEvent(event)
52+
})
53+
}
54+
})
55+
56+
const handleCreateUser = async (name, email, password, form) => {
57+
try {
58+
59+
/* Insert User to API REST VVVVVVVVVVVVVVVVVVV */
60+
await createUser(name, email, password);
61+
const event = new CustomEvent("register-ok", {
62+
detail: {
63+
message: 'You have successfully registered.',
64+
type: 'success'
65+
}
66+
});
67+
/* AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA */
68+
69+
form.dispatchEvent(event)
70+
setTimeout(() => {
71+
window.location = '/'
72+
}, 5000);
73+
74+
} catch (error) {
75+
76+
const event = new CustomEvent("register-error", {
77+
detail: error.message
78+
});
79+
80+
// This event is sent to "signup" as it is being listened to.
81+
form.dispatchEvent(event)
82+
}
83+
}
84+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
export const createUser = async (name, email, pw) => {
2+
try {
3+
const response = await fetch("http://127.0.0.1:8000/auth/register", {
4+
method: "POST",
5+
body: JSON.stringify({
6+
name,
7+
username: email,
8+
password: pw
9+
}),
10+
headers: {
11+
"Content-Type": "application/json"
12+
}
13+
});
14+
15+
if (!response.ok) {
16+
// If response is not OK, throw an error with the response message
17+
const data = await response.json();
18+
throw new Error(data.message || "Server error occurred.");
19+
}
20+
21+
} catch (error) {
22+
console.error('Error during user creation:', error);
23+
throw error;
24+
}
25+
};

src/js/modules/signup/signup.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { signUpController } from "./signUpController.js";
2+
import {notificationsController} from "../../components/notifications/notificationsController.js"
3+
4+
document.addEventListener("DOMContentLoaded", () => {
5+
6+
const registerForm = document.querySelector("form");
7+
const notifications = document.querySelector("#notifications");
8+
9+
const { showNotification } = notificationsController(notifications)
10+
11+
registerForm.addEventListener("register-error", (event) => {
12+
const message = event.detail;
13+
showNotification(message)
14+
})
15+
16+
registerForm.addEventListener("register-ok", (event) => {
17+
const message = event.detail.message;
18+
const type = event.detail.type;
19+
showNotification(message, type)
20+
})
21+
22+
signUpController(registerForm)
23+
})

src/js/utils/constants.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export const REGEXP = {
2+
mail: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
3+
}

views/signup.html

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>SignUp</title>
7+
<link rel="stylesheet" href="../src/styles/notifications.css">
8+
9+
</head>
10+
<body>
11+
<div id="notifications"></div>
12+
<form>
13+
<label for="name">Name: </label>
14+
<input
15+
id="name"
16+
name="name"
17+
type="text"
18+
placeholder="Introduce your name"
19+
/>
20+
21+
<label for="email">Email:</label>
22+
<input
23+
id="email"
24+
name="email"
25+
type="email"
26+
placeholder="Introduce your email"
27+
required
28+
/>
29+
30+
<label for="password">Password:</label>
31+
<input
32+
id="password"
33+
name="password"
34+
type="password"
35+
placeholder="Introduce your password"
36+
required
37+
minlength="6"
38+
/>
39+
40+
<label for="password-confirm">Confirm Password:</label>
41+
<input
42+
id="password-confirm"
43+
name="password-confirm"
44+
type="password"
45+
placeholder="Confirm your password"
46+
required
47+
minlength="6"
48+
/>
49+
50+
<button type="submit">Create User</button>
51+
</form>
52+
53+
<script type="module" src="../src/js/modules/signup/signup.js"></script>
54+
</body>
55+
</html>

0 commit comments

Comments
 (0)