Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Учебный проект: долгая прогулка #19

Merged
merged 23 commits into from
Feb 6, 2021
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
9585263
6.2 Add database sequelize models
ilyasidorchik Jan 17, 2021
02cc07c
6.2 Add script to fill database
ilyasidorchik Jan 17, 2021
11c9fa8
6.2 Refactor file-db: replace old logger
ilyasidorchik Jan 17, 2021
f2d91a9
6.2 Rewrite data services with sequelize
ilyasidorchik Jan 18, 2021
580dca0
6.2 Rewrite API with sequelize
ilyasidorchik Jan 18, 2021
1dd8d2a
6.2 Rewrite frontend server
ilyasidorchik Jan 18, 2021
b0d4cf9
6.2 Handle data for categories on index page
ilyasidorchik Jan 19, 2021
218c941
6.2 Handle data for offer
ilyasidorchik Jan 19, 2021
b7c5bcf
6.2 Try to fix categories e2e test
ilyasidorchik Jan 20, 2021
ab5290a
6.2 Fix API categories test
ilyasidorchik Jan 27, 2021
30b1a5b
6.2 Fix API search test
ilyasidorchik Jan 28, 2021
fdd3fe5
6.2 Fix API offers test
ilyasidorchik Jan 30, 2021
bdb53ac
Merge branch 'master' of github.com:ilyasidorchik/521287-buy-and-sell…
ilyasidorchik Jan 30, 2021
d37ab31
6.2 Remove obsolete cli command
ilyasidorchik Feb 1, 2021
f03f507
6.2 Name pug offers variable more clear
ilyasidorchik Feb 5, 2021
7cfadff
6.2 Comment unclear my/comments route
ilyasidorchik Feb 6, 2021
4b457ee
6.2 Refactor comment service
ilyasidorchik Feb 6, 2021
d8291ec
6.2 Name offer mock variables better
ilyasidorchik Feb 6, 2021
afd7aca
6.2 Update readme doc
ilyasidorchik Feb 6, 2021
32e60e0
6.2 Handle data for category page
ilyasidorchik Feb 6, 2021
71ae001
6.2 Name mock category variables better
ilyasidorchik Feb 6, 2021
f024279
6.2 Name offer pug variables more clear
ilyasidorchik Feb 6, 2021
8949777
6.2 Fix category template: return category list
ilyasidorchik Feb 6, 2021
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
File renamed without changes
File renamed without changes
522 changes: 494 additions & 28 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
"test": "npm run test::eslint && npm run jest"
},
"dependencies": {
"axios": "0.21.0",
"chalk": "4.1.0",
"cross-env": "7.0.2",
"dotenv": "8.2.0",
Expand All @@ -34,15 +33,17 @@
"pg": "8.5.1",
"pino": "6.7.0",
"pug": "3.0.0",
"sequelize": "6.3.5"
"sequelize": "6.4.0"
},
"devDependencies": {
"axios": "0.21.1",
"eslint": "7.11.0",
"eslint-config-htmlacademy": "0.6.0",
"jest": "26.5.3",
"nodemon": "2.0.5",
"pino-pretty": "4.3.0",
"pug-lint": "2.6.0",
"supertest": "5.0.0"
"sqlite3": "5.0.0",
"supertest": "6.1.1"
}
}
8 changes: 4 additions & 4 deletions src/express/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ class API {
return response.data;
}

getOffers() {
return this._load(`/offers`);
getOffers({comments} = {}) {
return this._load(`/offers`, {params: {comments}});
}

getOffer(id) {
Expand All @@ -33,8 +33,8 @@ class API {
return this._load(`/search`, {params: {query}});
}

getCategories() {
return this._load(`/categories`);
getCategories(count) {
return this._load(`/categories`, {params: {count}});
}

createOffer(data) {
Expand Down
File renamed without changes
7 changes: 5 additions & 2 deletions src/express/routes/main-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ const ROOT = `main`;
const mainRouter = new Router();

mainRouter.get(`/`, async (req, res) => {
const _offers = await api.getOffers();
const [_offers, categories] = await Promise.all([
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У нас это не класс, почему подчеркивание? Это же не приватный метод

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Потому что шаблонизатор «Паг 3» выдаёт ошибку, если переменная начинается с ключевого слова: в моём случае с of.

Баг в Паге 3

Copy link

@Krabaton Krabaton Feb 1, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

так тогда передавай {_offers: offers} в сам шаблон. а лучше (offersForPug: offers) чтобы понять было, что не просто так это сделали.

api.getOffers(),
api.getCategories(true),
]);

res.render(`${ROOT}/main`, {_offers});
res.render(`${ROOT}/main`, {_offers, categories});
});

mainRouter.get(`/search`, async (req, res) => {
Expand Down
2 changes: 1 addition & 1 deletion src/express/routes/my-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ myRouter.get(`/`, async (req, res) => {
});

myRouter.get(`/comments`, async (req, res) => {
const _offers = await api.getOffers();
const _offers = await api.getOffers({comments: true});

res.render(`${ROOT}/comments`, {_offers: _offers.slice(0, 3)});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужен поясняющий комментарий, почему мы так делаем. Отрезаем только первые три части массива.

});
Expand Down
19 changes: 16 additions & 3 deletions src/express/routes/offers-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,12 @@ const storage = multer.diskStorage({

const upload = multer({storage});

offersRouter.get(`/add`, (req, res) => res.render(`${ROOT}/add`));
offersRouter.get(`/add`, async (req, res) => {
const categories = await api.getCategories();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вопрос, что будет если сервис вернет ошибку?
Каждый await это потенциальная ошибка и обработки ее или нет или она не очевидна.

Copy link
Contributor Author

@ilyasidorchik ilyasidorchik Feb 6, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Связался с автором курса — будем обрабатывать ошибки и делать валидацию в следующем модуле.

Остальное исправил.


res.render(`${ROOT}/add`, {categories});
});

offersRouter.post(`/add`, upload.single(`avatar`), async (req, res) => {
const {file: {
filename: picture,
Expand Down Expand Up @@ -64,7 +69,15 @@ offersRouter.get(`/edit/:id`, async (req, res) => {
res.render(`${ROOT}/edit`, {offer, categories});
});

offersRouter.get(`/category/:id`, (req, res) => res.render(`${ROOT}/category`));
offersRouter.get(`/:id`, (req, res) => res.render(`${ROOT}/offer`));
offersRouter.get(`/:id`, async (req, res) => {
const {id} = req.params;

const _offer = await api.getOffer(id, true);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опять все вместе подчеркивание и await


res.render(`${ROOT}/offer`, {_offer});
});

offersRouter.get(`/category/:id`, (req, res) =>
res.render(`${ROOT}/category`));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мы в шаблон ничего не передаем? Вроде же конкретную категорию просим :id


module.exports = offersRouter;
7 changes: 7 additions & 0 deletions src/express/templates/layout.pug
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,15 @@ head
body
mixin ticketLabel(type)
span(class!=attributes.class || `ticket-card__label`) #{type === `OFFER` ? `Куплю` : `Продам`}

- const getRandomInt = (max) => Math.ceil(Math.random() * max);
mixin categoryImage(category)
- const idPadded = `0${getRandomInt(6)}`
img(src=`/img/cat${idPadded}.jpg` srcset=`img/cat${idPadded}@2x.jpg 2x` alt=category.name)

include partials/header.pug
block content
include partials/footer.pug

script(src='/js/vendor.js')
script(src='/js/main.js')
15 changes: 8 additions & 7 deletions src/express/templates/main/main.pug
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,24 @@ block content
.tickets-list__header
p.tickets-list__title Самое свежее
ul
each offer in _offers
each _offer in _offers
li.tickets-list__item
.ticket-card.ticket-card--color01
.ticket-card__img
img(src=`/img/${offer.picture}` alt=offer.title)
img(src=`/img/${_offer.picture}` alt=_offer.title)
.ticket-card__info
+ticketLabel(offer.type)
+ticketLabel(_offer.type)
.ticket-card__categories
a(href="#") #{offer.categories}
each category in _offer.categories
a(href="#") #{category.name}
.ticket-card__header
h3.ticket-card__title
a(href="#") #{offer.title}
a(href="#") #{_offer.title}
p.ticket-card__price
span.js-sum #{offer.sum}
span.js-sum #{_offer.sum}
| ₽
.ticket-card__desc
p #{offer.description}
p #{_offer.description}
section.tickets-list
h2.visually-hidden Самые обсуждаемые предложения
.tickets-list__wrapper
Expand Down
2 changes: 1 addition & 1 deletion src/express/templates/main/search.pug
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ block content
+ticketLabel(_offer.type)
.ticket-card__categories
each category of _offer.categories
a(href='#') #{category}
a(href='#') #{category.name}
.ticket-card__header
h3.ticket-card__title
a(href='#') #{_offer.title}
Expand Down
13 changes: 7 additions & 6 deletions src/express/templates/my/tickets.pug
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,20 @@ block content
a.tickets-list__btn.btn.btn--big(href='/offers/add')
span Новая публикация
ul
each offer in _offers
each _offer in _offers
li.tickets-list__item.js-card
.ticket-card.ticket-card--color01
.ticket-card__img
img(src=`/img/${offer.picture}` alt=offer.title)
img(src=`/img/${_offer.picture}` alt=_offer.title)
.ticket-card__info
+ticketLabel(offer.type)
+ticketLabel(_offer.type)
.ticket-card__categories
a(href='#') #{offer.category}
each category in _offer.categories
a(href='#') #{category.name}
.ticket-card__header
h3.ticket-card__title
a(href='#') #{offer.title}
a(href='#') #{_offer.title}
p.ticket-card__price
span.js-sum #{offer.sum}
span.js-sum #{_offer.sum}
| ₽
button.ticket-card__del.js-delete(type='button') Удалить
6 changes: 2 additions & 4 deletions src/express/templates/offers/add.pug
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,8 @@ block content
span Обязательное поле
.ticket-form__row
select#category-field.form__select.js-multiple-select(name='category' data-label='Выбрать категорию публикации')
option(value='1') Дом
option(value='2') Спорт и отдых
option(value='3') Авто
option(value='4') Электроника
each category in categories
option(value=category.id) #{category.name}
.ticket-form__row
.form__field.form__field--price
input#price-field.js-field.js-price(type='number' name='price' min='1' required)
Expand Down
4 changes: 2 additions & 2 deletions src/express/templates/offers/edit.pug
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ block content
span Обязательное поле
.ticket-form__row
select#category-field.form__select.js-multiple-select(name='category' data-label='Выбрать категорию публикации' multiple)
each category, index in categories
option(value=index selected=offer.categories.includes(category)) #{category}
each category in categories
option(value=category.id) #{category.name}
.ticket-form__row
.form__field.form__field--price
input#price-field.js-field.js-price(type='number' name='price' min='1' value=offer.price required)
Expand Down
63 changes: 33 additions & 30 deletions src/express/templates/offers/offer.pug
Original file line number Diff line number Diff line change
@@ -1,42 +1,53 @@
extends ../layout.pug

block content
-
const formatDate = (dateString) => {
const date = new Date(dateString);

return date.toLocaleString();
}

section.ticket
.ticket__wrapper
h1.visually-hidden Карточка объявления
.ticket__content
.ticket__img
img(src='img/ticket.jpg' srcset='img/[email protected] 2x' alt='Изображение товара')
img(src=`/img/${_offer.picture}.jpg`
srcset=`/img/${_offer.picture}@2x.jpg 2x`
alt=_offer.title)
.ticket__info
h2.ticket__title Мое старое кресло
h2.ticket__title #{_offer.title}
.ticket__header
p.ticket__price
span.js-sum 4000
span.js-sum #{_offer.sum}
| ₽
p.ticket__action ПРОДАМ
p.ticket__action #{_offer.type === `OFFER` ? `КУПЛЮ` : `ПРОДАМ`}
.ticket__desc
p Продам свое старое кресло, чтобы сидеть и читать книги зимними вечерами. Ножки мягкие, мой пол не царапают. Кресло почти новое – продаю, т.к. надоел серый цвет. Можно, конечно, накинуть плед и спасти ситуацию, но я все-таки хочу просто другое кресло. В общем оно на самом деле удобное и с ним все хорошо, просто нам пора расстаться.
p #{_offer.description}
.ticket__data
p
b Дата добавления:
span 20 ноября 2019
span #{formatDate(_offer.createdAt)}
p
b Автор:
a(href='#') Денис Шкатулкин
p
b Контакты:
a(href='mailto:[email protected]') [email protected]
ul.ticket__tags
li
a.category-tile.category-tile--small(href='#')
span.category-tile__image
img(src='img/cat.jpg' srcset='img/[email protected] 2x' alt='Иконка категории')
span.category-tile__label Дом
each category in _offer.categories
li
a.category-tile.category-tile--small(href='#')
span.category-tile__image
+categoryImage(category)
span.category-tile__label #{category.name}
li
a.category-tile.category-tile--small(href='#')
span.category-tile__image
img(src='img/cat04.jpg' srcset='img/[email protected] 2x' alt='Иконка категории')
span.category-tile__label Спорт и отдых

.ticket__comments
h2.ticket__subtitle Коментарии
.ticket__comment-form
Expand All @@ -51,24 +62,16 @@ block content
label(for='comment-field') Текст комментария
span Обязательное поле
button.comment-form__button.btn.btn--white.js-button(type='submit' disabled) Отправить

.ticket__comments-list
ul.comments-list
li
.comment-card
.comment-card__header
a.comment-card__avatar.avatar(href='#')
img(src='img/avatar02.jpg' srcset='img/[email protected] 2x' alt='Аватар пользователя')
p.comment-card__author Георгий Шпиц
.comment-card__content
p Что это за рухлядь? Стыдно такое даже фотографировать, не то, что продавать.
li
.comment-card
.comment-card__header
a.comment-card__avatar.avatar(href='#')
img(src='img/avatar03.jpg' srcset='img/[email protected] 2x' alt='Аватар пользователя')
p.comment-card__author Александр Бурый
.comment-card__content
p
| А можете доставить мне домой? Готов доплатить 300 сверху.
br
| Живу в центре прямо рядом с Моховой улицей. Готов купить прямо сейчас. Мой телефон 9032594748
if _offer.comments && _offer.comments.length
each comment in _offer.comments
li
.comment-card
.comment-card__header
a.comment-card__avatar.avatar(href='#')
img(src='img/avatar03.jpg' srcset='img/[email protected] 2x' alt='Аватар пользователя')
p.comment-card__author Александр Бурый
.comment-card__content
p #{comment.text}
51 changes: 8 additions & 43 deletions src/express/templates/partials/categories.pug
Original file line number Diff line number Diff line change
@@ -1,45 +1,10 @@
section.categories-list
h1.visually-hidden Сервис объявлений "Куплю - продам"
h1.visually-hidden Сервис объявлений «Куплю продам»
ul.categories-list__wrapper
li.categories-list__item
a.category-tile.category-tile--default(href='#')
span.category-tile__image
img(src='img/cat.jpg' srcset='img/[email protected] 2x' alt='Иконка категории')
span.category-tile__label
| Дом
span.category-tile__qty.js-qty 81
li.categories-list__item
a.category-tile.category-tile--default(href='#')
span.category-tile__image
img(src='img/cat02.jpg' srcset='img/[email protected] 2x' alt='Иконка категории')
span.category-tile__label
| Электроника
span.category-tile__qty.js-qty 62
li.categories-list__item
a.category-tile.category-tile--default(href='#')
span.category-tile__image
img(src='img/cat03.jpg' srcset='img/[email protected] 2x' alt='Иконка категории')
span.category-tile__label
| Одежда
span.category-tile__qty.js-qty 106
li.categories-list__item
a.category-tile.category-tile--default(href='#')
span.category-tile__image
img(src='img/cat04.jpg' srcset='img/[email protected] 2x' alt='Иконка категории')
span.category-tile__label
| Спорт/отдых
span.category-tile__qty.js-qty 86
li.categories-list__item
a.category-tile.category-tile--default(href='#')
span.category-tile__image
img(src='img/cat05.jpg' srcset='img/[email protected] 2x' alt='Иконка категории')
span.category-tile__label
| Авто
span.category-tile__qty.js-qty 34
li.categories-list__item
a.category-tile.category-tile--default(href='#')
span.category-tile__image
img(src='img/cat06.jpg' srcset='img/[email protected] 2x' alt='Иконка категории')
span.category-tile__label
| Книги
span.category-tile__qty.js-qty 92
each category in categories
li.categories-list__item
a.category-tile.category-tile--default(href='#')
span.category-tile__image
+categoryImage(category)
span.category-tile__label #{category.name}
span.category-tile__qty.js-qty #{category.count}
Loading