-
Notifications
You must be signed in to change notification settings - Fork 0
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | ||
} | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
|
||
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Может в будущем стрельнуть в ногу)