diff --git a/server/routers/gamehub/index.js b/server/routers/gamehub/index.js index 34af599..301a512 100644 --- a/server/routers/gamehub/index.js +++ b/server/routers/gamehub/index.js @@ -8,6 +8,10 @@ router.get("/update-like", (request, response) => { response.send(require("./json/gamepage/success.json")); }); +router.get("/add-to-cart", (request, response) => { + response.send(require("./json/home-page-data/games-in-cart.json")); +}); + router.get("/categories", (request, response) => { response.send(require("./json/home-page-data/all-games.json")); }); @@ -16,18 +20,32 @@ router.get("/favourites", (request, response) => { response.send(require("./json/home-page-data/all-games.json")); }); +// router.get("/shopping-cart", (request, response) => { +// response.send(require("../json/shopping-cart/success.json")); +// }); + router.get("/shopping-cart", (request, response) => { - response.send(require("./json/shopping-cart/success.json")); + response.send(require("./json/home-page-data/games-in-cart.json")); }); -router.get("/home", (request, response) => { - response.send(require("./json/home-page-data/success.json")); +// Добавляем поддержку разных ответов для /home +router.get("/home", (req, res) => { + if (stubs.home === "success") { + res.send(require("./json/home-page-data/success.json")); + } else if (stubs.home === "empty") { + res.send({ data: [] }); // Отправляем пустой массив + } else { + res.status(500).json({ success: false, message: "Server error" }); + } }); router.get("/all-games", (request, response) => { response.send(require("./json/home-page-data/all-games.json")); }); +const stubs = { + home: "success", +}; // // Маршрут для обновления лайков // router.post("/update-like", (request, response) => { @@ -42,18 +60,17 @@ router.get("/all-games", (request, response) => { // }); // }); - const fs = require("fs").promises; const path = require("path"); // Path to JSON file -const commentsFilePath = path.join(__dirname, "./json/gamepage/success.json"); +const commentsFilePath = path.join(__dirname, "../json/gamepage/success.json"); // Read JSON file async function readComments() { const data = await fs.readFile(commentsFilePath, "utf-8"); const parsedData = JSON.parse(data); - console.log("Прочитанные данные:", parsedData); // Логируем полученные данные + console.log("Прочитанные данные:", parsedData); // Логируем полученные данные return parsedData; } // Write to JSON file @@ -92,5 +109,137 @@ router.post("/update-like", async (req, res) => { } }); +// Путь к JSON-файлу с корзиной +const cartFilePath = path.join( + __dirname, + "../json/home-page-data/games-in-cart.json" +); + +// Функция для чтения JSON-файла +async function readCart() { + const data = await fs.readFile(cartFilePath, "utf-8"); + return JSON.parse(data); +} + +// Функция для записи в JSON-файл +async function writeCart(data) { + await fs.writeFile(cartFilePath, JSON.stringify(data, null, 2), "utf-8"); +} + +// Маршрут для добавления/удаления товара в корзине +router.post("/add-to-cart", async (req, res) => { + const { id, action } = req.body; + + // Проверка наличия id и action + if (id === undefined || action === undefined) { + return res + .status(400) + .json({ success: false, message: "Invalid id or action" }); + } + + try { + const cartData = await readCart(); + let ids = cartData.data.ids; + + if (action === "add") { + // Если action "add", добавляем товар, если его нет в корзине + if (!ids?.includes(id)) { + ids.push(id); + } + } else if (action === "remove") { + // Если action "remove", удаляем товар, если он есть в корзине + if (ids?.includes(id)) { + ids = ids.filter((item) => item !== id); + } + } else { + // Если action невалиден + return res + .status(400) + .json({ success: false, message: "Invalid action" }); + } + + // Записываем обновленные данные обратно в файл + cartData.data.ids = ids; + await writeCart(cartData); + + res.status(200).json({ + success: true, + message: "Cart updated successfully", + data: cartData.data, // Возвращаем обновленные данные + }); + } catch (error) { + console.error("Error updating cart:", error); + res.status(500).json({ success: false, message: "Server error" }); + } +}); module.exports = router; + +const createElement = (key, value, buttonTitle) => ` + +`; + +router.get("/admin/home", (request, response) => { + response.send(` +
+
+ Настройка данных для /home + ${createElement("home", "success", "Отдать успешный ответ")} + ${createElement("home", "empty", "Отдать пустой массив")} + ${createElement("home", "error", "Отдать ошибку")} +
+
+ `); +}); + + +router.get("/admin/game-page", (request, response) => { + response.send(` +
+
+ Настройка данных для /game-page + ${createElement("game-page", "success", "Отдать успешный ответ")} + ${createElement("game-page", "empty", "Отдать пустой массив")} + ${createElement("game-page", "error", "Отдать ошибку")} + +
+
+ `); +}); + +router.get("/admin/categories", (request, response) => { + response.send(` +
+
+ Настройка данных для /categories + ${createElement("categories", "success", "Отдать успешный ответ")} + ${createElement("categories", "empty", "Отдать пустой массив")} + ${createElement("categories", "error", "Отдать ошибку")} +
+
+ `); +}); + +router.get("/admin/favourites", (request, response) => { + response.send(` +
+
+ Настройка данных для /favourites + ${createElement("favourites", "success", "Отдать успешный ответ")} + ${createElement("favourites", "empty", "Отдать пустой массив")} + ${createElement("favourites", "error", "Отдать ошибку")} +
+
+ `); +}); + +router.get("/admin/set/:key/:value", (request, response) => { + const { key, value } = request.params; + stubs[key] = value; + response.send("Настройки обновлены!"); +}); \ No newline at end of file diff --git a/server/routers/gamehub/json/gamepage/success.json b/server/routers/gamehub/json/gamepage/success.json index c4b9801..958704e 100644 --- a/server/routers/gamehub/json/gamepage/success.json +++ b/server/routers/gamehub/json/gamepage/success.json @@ -5,28 +5,28 @@ { "username": "Пользователь1", "text": "Текст комментария 1", - "likes": 11, + "likes": 13, "rating": 8, "date": "2025-03-01T10:00:00Z" }, { "username": "Пользователь2", "text": "Текст комментария 2", - "likes": 7, + "likes": 10, "rating": 7, "date": "2025-01-01T10:00:00Z" }, { "username": "Пользователь3", "text": "Текст комментария 3", - "likes": 2, + "likes": 4, "rating": 3, "date": "2025-02-01T10:00:00Z" }, { "username": "Пользователь4", "text": "Текст комментария 4", - "likes": 15, + "likes": 18, "rating": 2, "date": "2025-12-01T10:00:00Z" } diff --git a/server/routers/gamehub/json/home-page-data/success.json b/server/routers/gamehub/json/home-page-data/success.json index bd83dcb..c393e06 100644 --- a/server/routers/gamehub/json/home-page-data/success.json +++ b/server/routers/gamehub/json/home-page-data/success.json @@ -105,23 +105,27 @@ { "image": "news1", "text": "Разработчики Delta Force: Hawk Ops представили крупномасштабный режим Havoc Warfare", - "imgPath": "img_news_1" + "imgPath": "img_news_1", + "link": "https://gamemag.ru/news/185583/delta-force-hawk-ops-gameplay-showcase-havoc-warfare" }, { "image": "news2", "text": "Первый трейлер Assassin’s Creed Shadows — с темнокожим самураем в феодальной Японии", - "imgPath": "img_news_2" + "imgPath": "img_news_2", + "link": "https://stopgame.ru/newsdata/62686/pervyy_trailer_assassin_s_creed_shadows_s_temnokozhim_samuraem_v_feodalnoy_yaponii" }, { "image": "news3", "text": "Призрак Цусимы» вышел на ПК — и уже ставит рекорды для Sony", - "imgPath": "img_news_3" + "imgPath": "img_news_3", + "link": "https://stopgame.ru/newsdata/62706/prizrak_cusimy_vyshel_na_pk_i_uzhe_stavit_rekordy_dlya_sony" }, { "image": "news4", - "text": "Авторы Skull and Bones расширяют планы на второй сезо", - "imgPath": "img_news_4" + "text": "Авторы Skull and Bones расширяют планы на второй сезон", + "imgPath": "img_news_4", + "link": "https://stopgame.ru/newsdata/62711/avtory_skull_and_bones_rasshiryayut_plany_na_vtoroy_sezon" } ] } -} +} \ No newline at end of file