Skip to content

Commit

Permalink
해시라우터 구현 (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
jch1223 authored Dec 19, 2024
1 parent f730785 commit 2d41d3d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/__tests__/advanced.hashRouter.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ beforeAll(async () => {
// DOM 초기화
window.alert = vi.fn();
document.body.innerHTML = '<div id="root"></div>';
await import("../main.hash.js");
await import("../main.hash.ts");
});

afterAll(() => {
Expand Down
5 changes: 5 additions & 0 deletions src/core/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ export const render = () => {
router.navigateTo(window.location.pathname);
});

window.addEventListener("hashchange", () => {
const pathname = window.location.hash.split("#")[1];
router.navigateTo(pathname);
});

window.addEventListener("submit", (e) => {
e.preventDefault();
});
Expand Down
27 changes: 23 additions & 4 deletions src/core/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { LoginPage } from "@/pages/Login";
import { ProfilePage } from "@/pages/Profile";
import { userStore } from "@/store/userStore";

const createRouter = (routes: { [key: string]: () => void }) => {
const createRouter = (routes: Record<string, () => void>) => {
return {
navigateTo(path: string) {
if (!Object.keys(routes).includes(path)) {
path = "/error";
routes["/error"]();
return;
}

history.pushState(null, "", path);
Expand All @@ -17,6 +18,21 @@ const createRouter = (routes: { [key: string]: () => void }) => {
};
};

const createHashRouter = (routes: Record<string, () => void>) => {
return {
navigateTo(path: string) {
if (!Object.keys(routes).includes(`${path}`)) {
window.location.hash = `#/error`;
routes["/error"]();
return;
}

window.location.hash = `#${path}`;
routes[path]();
},
};
};

const routeGuard = (render: () => void) => () => {
if (window.location.pathname !== "/login" && !userStore.getUser()) {
router.navigateTo("/login");
Expand All @@ -38,6 +54,9 @@ const routes = {
"/error": ErrorPage.render,
};

const router = createRouter(routes);
const browserRouter = createRouter(routes);
const hashRouter = createHashRouter(routes);

const router = window.location.hash ? hashRouter : browserRouter;

export { router };
export { router, hashRouter };

0 comments on commit 2d41d3d

Please sign in to comment.