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

Мехряков Матвей #52

Open
wants to merge 4 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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@

6. Сделай так, чтобы при клике на ссылку оплатить текущий заказ завершался и корзина очищалась

7. Добавь страницу `/login` на которой будет возможность заполнить своё имя. Чтобы сохранить имя используй [cookie()](https://expressjs.com/en/4x/api.html#res.cookie). Чтобы читать имя потребуются [cookies](https://expressjs.com/en/4x/api.html#req.cookies) и `cookie-parser` [middleware](https://expressjs.com/en/resources/middleware/cookie-parser.html).
7. Добавь страницу `/login` на которой будет возможность заполнить своё имя. Чтобы сохранить имя используй [cookie()](https://expressjs.com/en/4x/api.html#res.cookie). Чтобы читать имя потребуются [cookies](https://expressjs.com
/en/4x/api.html#req.cookies) и `cookie-parser` [middleware](https://expressjs.com/en/resources/middleware/cookie-parser.html).

Обрати внимание, что форма посылается GET запросом. Чтобы прочитать параметры используй [query](https://expressjs.com/en/4x/api.html#req.query). Не забудь поправить шаблон, чтобы в нём отображалось сохранённое имя.

Expand Down
96 changes: 83 additions & 13 deletions index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,40 @@ import cookieParser from "cookie-parser";
const rootDir = process.cwd();
const port = 3000;
const app = express();
let customerOrders = {}

const items = {
"Americano": {
name: "Americano",
image: '/static/img/americano.jpg',
price: 999,
},
"Cappuccino": {
name: "Cappuccino",
image: "/static/img/cappuccino.jpg",
price: 999
},
"Espresso": {
name: "Espresso",
image: '/static/img/espresso.jpg',
price: 111,
},
"Flat white": {
name: "Flat white",
image: '/static/img/flat-white.jpg',
price: 222,
},
"Latte": {
name: "Latte",
image: '/static/img/latte.jpg',
price: 333,
},
"Latte Macchiato": {
name: "Latte Macchiato",
image: '/static/img/latte-macchiato.jpg',
price: 433,
},
};

// Выбираем в качестве движка шаблонов Handlebars
app.set("view engine", "hbs");
Expand All @@ -20,38 +54,74 @@ app.engine(
})
);

// 1
// app.use(express.static('static'))

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

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 },
],
title: "overpriced coffee",
items: Object.values(items),
});
});

app.get("/buy/:name", (req, res) => {
res.status(501).end();
let item = items[req.params.name];
let username = req.cookies.username || "Аноним";
if (!(username in customerOrders)) {
customerOrders[username] = [];
}
customerOrders[username].push(items[req.params.name])
//cartContents.push(item);
//sum += item.price;
res.redirect('/menu');
});

app.get("/cart", (req, res) => {
res.status(501).end();
let username = req.cookies.username || "Аноним";
let order = [];
let userPrice = 0;
if(username in customerOrders) {
order = customerOrders[username];
userPrice = customerOrders[username].reduce((s, current) => s + current.price, 0)
}

res.render("cart", {
layout: "default",
title: 'корзина',
cartContents: order,
sum: userPrice,
});
});

app.post("/cart", (req, res) => {
res.status(501).end();
res.render("cart", {
layout: "default",
cartContents: [],
title: "Корзина",
sum: 0,
});
});


app.get("/login", (req, res) => {
res.status(501).end();
const username = req.query.username || req.cookies.username || "Аноним";
res.cookie("username", username);
res.render("login", {
layout: "default",
title: "Личный кабинет",
username: username,
});
});


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