Skip to content

Commit

Permalink
refactor: 해시 라우터 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
nogy21 committed Dec 19, 2024
1 parent d3977db commit 7e08a28
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions src/router.js → src/routers/router.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { userStore } from "./store/userStore";
import { userStore } from "../store/userStore";

const AUTH_REQUIRED_PAGES = ["/profile"];

export default class Router {
#routes = {};

Expand All @@ -10,16 +11,19 @@ export default class Router {

init() {
this.handleEventListeners();
// const hash = window.location.hash;
// console.log("🚀 ~ Router ~ init ~ hash:", hash);
const path = window.location.pathname;
// console.log("🚀 ~ Router ~ init ~ path:", path);
// this.navigate(hash ?? path);
const path = this.isHash()
? window.location.hash
: window.location.pathname;

this.navigate(path);
}

navigate(path) {
const root = document.getElementById("root");

if (this.isHash()) {
path = location.hash.slice(1) || "/";
}
const authenticatedPath = this.checkAuth(path);
const render = this.#routes[authenticatedPath] || this.#routes["/404"];

Expand All @@ -28,18 +32,21 @@ export default class Router {

checkAuth(path) {
let authenticatedPath = path;

if (AUTH_REQUIRED_PAGES.includes(path) && !userStore.isLoggedIn()) {
alert("로그인이 필요한 페이지입니다.");
authenticatedPath = "/login";
} else if (path === "/login" && userStore.isLoggedIn()) {
alert("이미 로그인되어 있습니다.");
authenticatedPath = "/";
}

return authenticatedPath;
}

handleEventListeners() {
this.handleLinkClick();
this.handleHashChange();
this.handlePopstate();
}

Expand All @@ -62,8 +69,7 @@ export default class Router {
e.preventDefault();

const href = target.getAttribute("href");
const isHash = location.hash.slice(1);
if (isHash) {
if (this.isHash()) {
window.location.hash = href;
return;
}
Expand All @@ -72,4 +78,8 @@ export default class Router {
}
});
}

isHash() {
return location.hash && location.hash.startsWith("#");
}
}

0 comments on commit 7e08a28

Please sign in to comment.