Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 2 additions & 55 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,61 +7,8 @@
</head>

<body>
<div class="container">
<ul class="comments">
<p>Загрузка</p>
<!--<li class="comment">
<div class="comment-header">
<div>Глеб Фокин</div>
<div>12.02.22 12:18</div>
</div>
<div class="comment-body">
<div class="comment-text">
Это будет первый комментарий на этой странице
</div>
</div>
<div class="comment-footer">
<div class="likes">
<span class="likes-counter">3</span>
<button class="like-button"></button>
</div>
</div>
</li>
<li class="comment">
<div class="comment-header">
<div>Варвара Н.</div>
<div>13.02.22 19:22</div>
</div>
<div class="comment-body">
<div class="comment-text">
Мне нравится как оформлена эта страница! ❤
</div>
</div>
<div class="comment-footer">
<div class="likes">
<span class="likes-counter">75</span>
<button class="like-button -active-like"></button>
</div>
</div>
</li>-->
</ul>
<div class="add-form">
<input
type="text"
class="add-form-name"
placeholder="Введите ваше имя"
/>
<textarea
type="textarea"
class="add-form-text"
placeholder="Введите ваш коментарий"
rows="4"
></textarea>
<div class="add-form-row">
<button class="add-form-button">Написать</button>
</div>
</div>
</div>
<div id="header" class="header"></div>
<div id="app" class="container">Загрузка ...</div>
</body>

<script type="module" src="./index.js"></script>
Expand Down
8 changes: 2 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
import { fetchGetComments } from './modules/fetchGetComments.js';
import { addClickBtnAddComment } from './modules/eventsBtnAddComment.js';
import { renderComments } from './modules/renderComments.js';

const API = 'https://wedev-api.sky.pro/api/v1/arusskov/comments';

fetchGetComments(API);
addClickBtnAddComment(API);
renderComments();
29 changes: 29 additions & 0 deletions modules/Login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const hostLogin = 'https://wedev-api.sky.pro/api/user/login';

export function Login(login, password) {
return fetch(hostLogin, {
method: 'POST',
body: JSON.stringify({ login, password }),
})
.then((response) => {
if (response.status === 201) {
return response.json();
} else {
if (response.status === 400) {
throw new Error('400');
} else {
throw new Error('Что то пошло не так');
}
}
})
.catch((error) => {
switch (error.message) {
case '400':
alert('Не верный логин или пароль');
break;
default:
alert('Что то пошло не так');
break;
}
});
}
54 changes: 54 additions & 0 deletions modules/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { user } from './user.js';

const host = 'https://wedev-api.sky.pro/api/v2/avrusskov-test/comments';

export function getComments() {
return fetch(host, { method: 'GET' }).then((response) => {
return response.json();
});
}

export function getCommentsAuthorazation() {
return fetch(host, {
method: 'GET',
headers: { Authorization: `Bearer ${user.token}` },
}).then((response) => {
return response.json();
});
}

export function postComment(newComment) {
return fetch(host, {
method: 'POST',
headers: { Authorization: `Bearer ${user.token}` },
body: JSON.stringify(newComment),
})
.then((responce) => {
if (responce.status === 201) {
return;
} else {
if (responce.status === 400) {
throw new Error('400');
}
}
})
.catch((error) => {
switch (error.message) {
case '400':
alert('Имя и комментарий должны быть не короче 3 символов');
break;
default:
alert('Кажется, у вас сломался интернет, попробуйте позже');
break;
}
});
}

export function updateLike(id) {
return fetch(`${host}/${id}/toggle-like`, {
method: 'POST',
headers: { Authorization: `Bearer ${user.token}` },
}).then((response) => {
return response.json();
});
}
82 changes: 13 additions & 69 deletions modules/eventsBtnAddComment.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,13 @@
import { replaceSymbol } from './replace.js';
import { fetchGetComments } from './fetchGetComments.js';
import { removeClassError, replaceSymbol } from './helpers.js';
import { postComment } from './api.js';
import { renderComments } from './renderComments.js';

let btnWrite = document.querySelector('.add-form-button');
let inputName = document.querySelector('.add-form-name');
let inputText = document.querySelector('.add-form-text');
const formAddComment = document.querySelector('.add-form');
const container = document.querySelector('.container');
async function clickAddComment() {
const inputText = document.querySelector('.add-form-text');
const formAddComment = document.querySelector('.add-form');
const container = document.querySelector('.container');

function removeClassError(input) {
input.classList.remove('input-error');
}

function clickAddComment(API) {
if (inputName.value === '' || inputText.value === '') {
if (inputName.value === '') {
inputName.classList.add('input-error');

setTimeout(() => removeClassError(inputName), 2000);
}
if (inputText.value === '') {
if (inputText.value === '') {
inputText.classList.add('input-error');

Expand All @@ -27,63 +17,17 @@ function clickAddComment(API) {
return;
}

const newComment = {
text: replaceSymbol(inputText.value),
name: replaceSymbol(inputName.value),
forceError: true,
};

formAddComment.style.display = 'none';

const loaderText = document.createElement('p');
loaderText.textContent = 'Комментарий добавляется';
container.appendChild(loaderText);

let isCrashServer = false;

fetch(API, {
method: 'POST',
body: JSON.stringify(newComment),
})
.then((responce) => {
if (responce.status === 201) {
inputName.value = '';
inputText.value = '';

return fetchGetComments(API);
} else {
if (responce.status === 400) {
throw new Error('400');
}

if (responce.status === 500) {
isCrashServer = true;
clickAddComment(API);
}
}
})
.catch((error) => {
switch (error.message) {
case '400':
alert('Имя и комментарий должны быть не короче 3 символов');
break;
case '500':
alert('Сервер сломался, попробуй позже');
break;
default:
alert('Кажется, у вас сломался интернет, попробуйте позже');
break;
}
})
.finally(() => {
container.removeChild(loaderText);

if (!isCrashServer) {
formAddComment.style.display = 'flex';
}
});
await postComment({ text: replaceSymbol(inputText.value) });
renderComments();
}

export function addClickBtnAddComment(API) {
btnWrite.addEventListener('click', () => clickAddComment(API));
export function addClickBtnAddComment() {
const btnWrite = document.getElementById('write-button');
btnWrite.addEventListener('click', clickAddComment);
}
32 changes: 13 additions & 19 deletions modules/eventsComment.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
import { renderComments } from './render.js';
import { updateLike } from './api.js';
import { comments } from './comments.js';

function delay(interval = 300) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, interval);
});
}
import { renderComments } from './renderComments.js';
import { user } from './user.js';

export function addClickBtnLike() {
const arrayBtnLike = document.querySelectorAll('.like-button');
Expand All @@ -16,18 +10,18 @@ export function addClickBtnLike() {
btnLike.addEventListener('click', (event) => {
event.stopPropagation();

btnLike.classList.add('loading-like');
console.log(btnLike.classList);
if (Object.keys(user).length !== 0) {
const index = btnLike.dataset.index;

const index = btnLike.dataset.index;
updateLike(comments[index].id).then((data) => {
comments[index].likes = data.result.likes;
comments[index].isLiked = data.result.isLiked;

delay(2000).then(() => {
comments[index].isLiked
? comments[index].likes--
: comments[index].likes++;
comments[index].isLiked = !comments[index].isLiked;
renderComments();
});
renderComments();
});
} else {
alert('Нужно авторизоваться');
}
});
}
}
Expand Down
13 changes: 0 additions & 13 deletions modules/fetchGetComments.js

This file was deleted.

4 changes: 4 additions & 0 deletions modules/replace.js → modules/helpers.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
export function replaceSymbol(text) {
return text.replaceAll('<', '&#706;').replaceAll('>', '&#707;');
}

export function removeClassError(input) {
input.classList.remove('input-error');
}
30 changes: 30 additions & 0 deletions modules/localStorage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { updateUser } from './user.js';

export function setLocalStorage(user) {
for (let key in user) {
localStorage.setItem(key, user[key]);
}
}

export function getLocalStorage() {
const newUser = {};
newUser['_id'] = localStorage.getItem('_id');
newUser['imageUrl'] = localStorage.getItem('imageUrl');
newUser['login'] = localStorage.getItem('login');
newUser['name'] = localStorage.getItem('name');
newUser['password'] = localStorage.getItem('password');
newUser['token'] = localStorage.getItem('token');

return newUser;
}

export function clearLocalStorage() {
localStorage.removeItem('_id');
localStorage.removeItem('imageUrl');
localStorage.removeItem('login');
localStorage.removeItem('name');
localStorage.removeItem('password');
localStorage.removeItem('token');

updateUser({});
}
29 changes: 29 additions & 0 deletions modules/registration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const hostRegistration = 'https://wedev-api.sky.pro/api/user';

export function Registration(name, login, password) {
return fetch(hostRegistration, {
method: 'POST',
body: JSON.stringify({ name, login, password }),
})
.then((response) => {
if (response.status === 201) {
return response.json();
} else {
if (response.status === 400) {
throw new Error('400');
} else {
throw new Error('Что то пошло не так');
}
}
})
.catch((error) => {
switch (error.message) {
case '400':
alert('Пользователь с таким логином уже есть');
break;
default:
alert('Что то пошло не так');
break;
}
});
}
Loading