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

Горохов Денис #51

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
147 changes: 122 additions & 25 deletions index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,51 +7,148 @@ const rootDir = process.cwd();
const port = 3000;
const app = express();

// Выбираем в качестве движка шаблонов Handlebars
class Item {
name;
image;
price;

constructor(name, image, price) {
this.name = name;
this.image = image;
this.price = price;
}
}

class Cart {
items;

constructor(items = []) {
this.items = items;
}

get sum() {
return this.items
.map(item => item.price)
.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
}

getCopy() {
return new Cart(this.items.slice());
}

reset() {
this.items = [];
}
}

class UserData {
name;
history;
#cart;

constructor(name = 'Аноним') {
this.name = name;
this.history = [];
}

get cart() {
if (!this.#cart) {
this.#cart = new Cart();
}

return this.#cart;
}
}

const items = [
new Item('Americano', '/static/img/americano.jpg', 999),
new Item('Cappuccino', '/static/img/cappuccino.jpg', 899),
new Item('Espresso', '/static/img/espresso.jpg', 299),
new Item('Flat white', '/static/img/flat-white.jpg', 599),
new Item('Latte', '/static/img/latte.jpg', 399),
new Item('Latte Macchiato', '/static/img/latte-macchiato.jpg', 699)
];

const users = [];
let currentUser = new UserData();

app.set("view engine", "hbs");
// Настраиваем пути и дефолтный view

app.engine(
"hbs",
hbs({
extname: "hbs",
defaultView: "default",
layoutsDir: path.join(rootDir, "/views/layouts/"),
partialsDir: path.join(rootDir, "/views/partials/"),
})
"hbs",
hbs({
extname: "hbs",
defaultView: "default",
layoutsDir: path.join(rootDir, "/views/layouts/"),
partialsDir: path.join(rootDir, "/views/partials/"),
})
);

app.use('/static', express.static('static'));
app.use(cookieParser());

app.get("/", (_, res) => {
res.sendFile(path.join(rootDir, "/static/html/index.html"));
res.redirect('/menu');
});

app.get("/menu", (_, res) => {
res.render("menu", {
layout: "default",
items: [
{
name: "Americano",
image: "/static/img/americano.jpg",
price: 999,
},
{ name: "Cappuccino", image: "/static/img/cappuccino.jpg", price: 999 },
],
});
res.render("menu", {
layout: "default",
title: 'Overpriced Coffee',
items,
});
});

app.get("/buy/:name", (req, res) => {
res.status(501).end();
const item = items.find(item => item.name === req.params.name);
currentUser.cart.items.push(item);
res.redirect('/menu');
});

app.get("/cart", (req, res) => {
res.status(501).end();
res.render('cart', {
layout: 'default',
title: 'Cart',
items: currentUser.cart.items,
sum: currentUser.cart.sum
})
});

app.post("/cart", (req, res) => {
res.status(501).end();
const copyCart = currentUser.cart.getCopy();
currentUser.history.unshift(copyCart);
currentUser.cart.reset();
res.redirect('/menu');
});

app.get("/login", (req, res) => {
res.status(501).end();
const username = req.query.username || req.cookies.username;
currentUser = getCurrentUser(username);

res.cookie('username', username);
res.render('login', {
layout: 'default',
title: 'Login',
username,
})
});

app.get('/history', (req, res) => {
res.render('history', {
layout: 'default',
title: 'History',
carts: currentUser.history
})
})

app.listen(port, () => console.log(`App listening on port ${port}`));

function getCurrentUser(username) {
let user = users.find(user => user.name === username);
if (!user) {
user = new UserData(username);
users.push(user);
}

return user;
}
39 changes: 26 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
}
},
"dependencies": {
"cookie-parser": "^1.4.4",
"cookie-parser": "^1.4.6",
"express": "^4.17.1",
"express-handlebars": "^3.1.0",
"nodemon": "^2.0.6"
Expand Down
7 changes: 5 additions & 2 deletions static/js/theme.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
const themeSwitch = document.querySelector(".theme__switch input");
const root = document.querySelector(":root");
const defaultState = root.classList.contains("dark");
const extraTheme = 'dark';
const defaultState = root.classList.contains(extraTheme);

themeSwitch.checked = defaultState;
localStorage.getItem('theme') === extraTheme && root.classList.toggle(extraTheme);
themeSwitch.addEventListener("click", () => {
root.classList.toggle("dark");
root.classList.toggle(extraTheme);
localStorage.setItem('theme', root.classList.contains(extraTheme) ? extraTheme : 'default');
});
17 changes: 17 additions & 0 deletions views/cart.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<div>
<section class="cart__total">
<div>Итого к оплате: {{sum}} ₽</div>
<form class="form" method="post">
<input class="action" type="submit" value="оплатить"/>
</form>
</section>
<ul class="coffee__list">
{{#each items}}
<li>
<header class="coffee__name">{{name}}</header>
<img src="{{image}}" alt="{{name}}">
<footer>{{price}} ₽</footer>
</li>
{{/each}}
</ul>
</div>
13 changes: 13 additions & 0 deletions views/history.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<div>
{{#each carts}}
<ul class="coffee__list">
{{#each items}}
<li>
<header class="coffee__name">{{name}}</header>
<img src="{{image}}" alt="{{name}}">
<footer>{{price}} ₽</footer>
</li>
{{/each}}
</ul>
{{/each}}
</div>
4 changes: 2 additions & 2 deletions views/layouts/default.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

<head>
<meta charset="utf-8">
<title>Overpriced Coffee</title>
<title>{{title}}</title>
<link rel="stylesheet" href="/static/css/index.css" />
<script type="module" src="/static/js/theme.mjs"></script>
</head>
{{> header}}

<body class="layout">
{{> header}}
<main>{{{body}}}</main>
{{> footer}}
</body>
Expand Down
10 changes: 10 additions & 0 deletions views/login.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<div>
<section class="user__hello">Привет, {{username}}!</section>
<form class="form" method="get">
<label class="label" for="username">
Зовите меня
<input id="username" name="username" type="text" value="{{username}}"/> !
</label>
<input class="action" type="submit" value="Сохранить"/>
</form>
</div>
1 change: 1 addition & 0 deletions views/partials/header.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<ul>
<li><a class="link" href="/menu">Меню</a></li>
<li><a class="link" href="/cart">Корзина</a></li>
<li><a class="link" href="/history">История</a></li>
<li><a class="link" href="/login">Личный кабинет</a></li>
</ul>
</nav>
Expand Down