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

Добавил интеграцию с бэкендом. Сделал отдельный модуль для http запросов. Настроил корсы #8

Merged
merged 4 commits into from
Feb 25, 2025
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
8 changes: 5 additions & 3 deletions build.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#!/bin/bash
mkdir -p public/build
handlebars -m public/src/pages/restaurantPage.hbs -f public/build/restaurantPage.js
handlebars -m public/src/pages/restaurantList.hbs -f public/build/restaurantList.js
handlebars -m public/src/components/header.hbs -f public/build/header.js
handlebars -m public/src/pages/restaurantPage/restaurantPage.hbs -f public/build/restaurantPage.js
handlebars -m public/src/pages/restaurantList/restaurantList.hbs -f public/build/restaurantList.js
handlebars -m public/src/pages/loginPage/loginPage.hbs -f public/build/loginPage.js
handlebars -m public/src/pages/registerPage/registerPage.hbs -f public/build/registerPage.js
handlebars -m public/src/components/header/header.hbs -f public/build/header.js
handlebars -m public/src/components/restaurantCard.hbs -f public/build/restaurantCard.js
1 change: 1 addition & 0 deletions public/build/loginPage.js

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

1 change: 1 addition & 0 deletions public/build/registerPage.js

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

1 change: 1 addition & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<head>
<meta charset="utf-8">
<title>Handlebars test</title>
<base href="/" />
</head>
<body>
<div id="root"></div>
Expand Down
76 changes: 8 additions & 68 deletions public/index.js
Original file line number Diff line number Diff line change
@@ -1,79 +1,19 @@
import "./build/restaurantList.js";
import "./build/restaurantPage.js";
import "./build/loginPage.js";
import "./build/registerPage.js";
import "./build/header.js";
import "./build/restaurantCard.js"
import * as requests from "./src/modules/requests.js"
import "./build/restaurantCard.js";
import {initRouting} from "./src/modules/routing.js";
import Header from "./src/components/header/header.js";

const rootElement = document.getElementById("root");
const pageElement = document.createElement("main");

rootElement.appendChild(pageElement);

Handlebars.registerPartial("restaurantCard", Handlebars.templates["restaurantCard.hbs"]);

function renderHeader() {
const template = Handlebars.templates["header.hbs"];
rootElement.insertAdjacentHTML("afterbegin", template());

document.getElementsByClassName("logo")[0].addEventListener("click", () => {
renderRestaurantList();
history.pushState({}, "", "/");
})
}

async function renderRestaurantList() {
try {
let restaurantList = await requests.getRestaurantList();
if (!restaurantList) throw new Error("Empty restaurant list");
const template = Handlebars.templates["restaurantList.hbs"];
pageElement.innerHTML = template({ restaurantList });

document.querySelectorAll(".restaurant-card").forEach(card => {
card.addEventListener("click", () => {
const restaurantId = card.dataset.id;
renderRestaurantPage(restaurantId);
history.pushState({ id: restaurantId }, "", `/restaurants/${restaurantId}`);
});
});

} catch (error) {
console.error("Error rendering restaurant list:", error);
}
}

async function renderRestaurantPage(id) {
pageElement.innerHTML = '';
try {
let restaurantDetail = await requests.getRestaurantById(id);
if (!restaurantDetail) throw new Error("Empty restaurant list");
const currentTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
let openStatus;
if (restaurantDetail.workingHours.open < currentTime && restaurantDetail.workingHours.closed > currentTime)
openStatus = "Open"
else
openStatus = "Closed"
const template = Handlebars.templates["restaurantPage.hbs"];
pageElement.innerHTML = template({ restaurantDetail, openStatus });
} catch (error) {
console.error("Error rendering restaurant list:", error);
}
}

window.addEventListener('popstate', (event) => {
const restaurantId = event.state ? event.state.id : null;
if (restaurantId) {
renderRestaurantPage(restaurantId);
} else {
renderRestaurantList();
}
});

const currentPath = window.location.pathname;
if (currentPath.startsWith("/restaurants/")) {
const restaurantId = currentPath.split("/")[2];
renderRestaurantPage(restaurantId);
} else {
renderRestaurantList();
}
initRouting(pageElement);

renderHeader();
const header = new Header(rootElement);
header.render();
28 changes: 28 additions & 0 deletions public/src/components/header/header.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import goToPage from "../../modules/routing.js";

export default class Header {
constructor(parent) {
this.parent = parent;
this.template = Handlebars.templates["header.hbs"];
}

render() {
this.parent.insertAdjacentHTML("afterbegin", this.template());
this._addEventListeners();
}

_addEventListeners() {
document.addEventListener("click", (event) => {
const logo = event.target.closest(".logo");
const loginButton = event.target.closest(".login-button");

if (logo) {
goToPage('home');
}

if (loginButton) {
goToPage('loginPage');
}
});
}
}
122 changes: 122 additions & 0 deletions public/src/modules/ajax.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import {decode, timeout} from "./utils.js";

/** @typedef {Promise<{create_time: string, image_path: string, id: string, username: string}>} UserData **/


const isDebug = false;

const REQUEST_TIMEOUT = 2000;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Может в будущем стрельнуть в ногу)


const baseUrl = `https://${isDebug ? "127.0.0.1" : "doordashers.ru"}:8443/api`;

const methods = {
POST: "POST",
GET: "GET",
DELETE: "DELETE",
PUT: "PUT"
};

let JWT = null;

JWT = window.localStorage.getItem("Authorization");

/**
* Базовый запрос
* @param method {methods}
* @param url {string}
* @param data {any}
* @param params {Dict<string, string>}
* @returns UserDataResponse
*/
const baseRequest = async (method, url, data = null, params=null) => {
const options = {
method: method,
mode: "cors",
credentials: "include",
signal: timeout(REQUEST_TIMEOUT),
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
}
};

if (JWT !== null) {
options.headers.Authorization = JWT;
}

if (data !== null) {
options.body = JSON.stringify(data);
}

let query_url = new URL(baseUrl + url);
if (params != null) {
query_url.search = new URLSearchParams(params);
}

try{
const response = await fetch(query_url.toString(), options).catch(() => {
//toasts.error("Ошибка", "Что-то пошло не так");
});
let body = null;
try {
body = await response.json();
} catch (err) {
console.log("no body");
}
if (response.headers.get("Authorization") !== null) {
JWT = response.headers.get("Authorization");
window.localStorage.setItem("Authorization", JWT);
}
return {status: response.status, body};
} catch (err) {
console.log(err);
return {status: 503, body: {message: err}};
}
};


class RestaurantsRequests {
#baseUrl = "/restaurants";

/**
* Получение списка всех ресторанов
* @returns {Promise<{message}|{any}>}
*/
GetAll = async (params=null) => {

const {status, body} = await baseRequest(
methods.GET,
this.#baseUrl + "/list",
null,
params
);

if (status === 200) {
return body;
} else {
throw Error(body.message);
}
};

/**
* Получение одного ресторана
* @param id {number} - id ресторана
* @returns {Promise<*>}
*/
Get = async (id) => {

const {status, body} = await baseRequest(
methods.GET,
this.#baseUrl + "/" + id,
null
);

if (status === 200) {
return body;
} else {
throw Error(body.message);
}
};
}

export const AppRestaurantRequests = new RestaurantsRequests();
4 changes: 2 additions & 2 deletions public/src/modules/requests.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export async function getRestaurantList() {
const url = "http://localhost:3000/restaurants";
const url = "http://localhost:3000/api/restaurants";
try {
const response = await fetch(url);
if (!response.ok) {
Expand All @@ -12,7 +12,7 @@ export async function getRestaurantList() {
}

export async function getRestaurantById(id) {
const url = `http://localhost:3000/restaurants/${id}`;
const url = `http://localhost:3000/api/restaurants/${id}`;
try {
const response = await fetch(url);
if (!response.ok) {
Expand Down
61 changes: 61 additions & 0 deletions public/src/modules/routing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import RestaurantList from "../pages/restaurantList/restaurantList.js";
import RestaurantPage from "../pages/restaurantPage/restaurantPage.js";
import LoginPage from "../pages/loginPage/loginPage.js";
import RegisterPage from "../pages/registerPage/registerPage.js";

let parentElement;

const config = {
home: {
href: '/',
class: RestaurantList,
},
restaurantPage: {
href: '/restaurants/',
class: RestaurantPage,
},
loginPage: {
href: '/login',
class: LoginPage,
},
registerPage: {
href: '/register',
class: RegisterPage,
}
};


export function initRouting(parent) {
parentElement = parent;
handleRouteChange();

window.addEventListener("popstate", handleRouteChange); // Обработчик кнопок "назад"/"вперёд"
}

function handleRouteChange() {
const currentPath = window.location.pathname;

if (currentPath === "/") {
goToPage('home', null, false);
return;
}
for (const [page, { href }] of Object.entries(config).slice(1)) {
if (currentPath.startsWith(href)) {
const id = currentPath.split("/")[2] || null;
return goToPage(page, id, false);
}
}
}

export default async function goToPage(page, id = null, shouldPushState = true) {
parentElement.innerHTML = '';
if (shouldPushState) {
if (id) {
history.pushState({ id: id }, "", `${config[page].href}${id}`);
} else {
history.pushState({}, "", config[page].href);
}
}
const pageClass = new config[page].class(parentElement, id)
pageClass.render()
}
32 changes: 32 additions & 0 deletions public/src/modules/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Обрезает переданную строку, если она длиннее, чем n символов
* @param str {string} исходная строка
* @param n {number} максимальная длинна строки, которая не будет обрезана
* @returns {string}
*/
export function truncate(str, n){
return (str.length > n) ? str.slice(0, n-1) + "..." : str;
}

/**
* Декодирует строку из base64 в unicode
* @param raw {string} закодированная строка
* @returns {Object} декодированный объект
*/
export function decode(raw) {
const decoded = atob(raw);
const bytes = Uint8Array.from(decoded, (m) => m.codePointAt(0));
return JSON.parse(new TextDecoder().decode(bytes));
}


/**
* Определеяет максимальную задержку в ожидании ответа от сервера
* @param ms - время в милисекундах
* @returns {AbortSignal}
*/
export function timeout(ms) {
const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), ms);
return ctrl.signal;
}
9 changes: 9 additions & 0 deletions public/src/pages/loginPage/loginPage.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<div class="login-form">
<h2>Войти</h2>
<form>
<input type="email" placeholder="Электронная почта" required>
<input type="password" placeholder="Пароль" required>
<button type="submit">Войти</button>
</form>
<a class="signup-link">Ещё не зарегистрированы?</a>
</div>
Loading
Loading