v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
import { Router, RouteMatch } from './Router';
import { createLogger } from '../utils/Logger';
const logger = createLogger('RouteResolver');
/**
* 라우트 변경 콜백 함수 타입
*/
export type RouteChangeCallback = (match: RouteMatch | null) => void;
/**
* RouteResolver 클래스
*
* 브라우저 History API와 통합되어 라우트 변경을 감지하고 처리합니다.
* popstate 이벤트를 감지하여 브라우저 뒤로가기/앞으로가기를 처리합니다.
*/
export class RouteResolver {
private router: Router;
private onRouteChange: RouteChangeCallback | null = null;
private isInitialized = false;
constructor(router: Router) {
this.router = router;
}
/**
* RouteResolver를 초기화합니다.
*
* - router.loadRoutes()를 호출하여 라우트 목록을 로드합니다.
* - popstate 이벤트 리스너를 등록합니다.
* - 초기 라우트를 해석합니다.
*
* @param callback - 라우트 변경 시 호출될 콜백 함수
*/
async init(callback: RouteChangeCallback): Promise<void> {
if (this.isInitialized) {
logger.warn('RouteResolver is already initialized');
return;
}
this.onRouteChange = callback;
// 라우트 목록 로드
await this.router.loadRoutes();
// popstate 이벤트 리스너 등록 (뒤로가기/앞으로가기)
window.addEventListener('popstate', this.handlePopState);
this.isInitialized = true;
// 초기 라우트 해석
this.resolve();
}
/**
* popstate 이벤트 핸들러
*
* 브라우저 뒤로가기/앞으로가기 시 호출됩니다.
*/
private handlePopState = (): void => {
this.resolve();
};
/**
* 현재 URL을 router.match()로 매칭하고 onRouteChange 콜백을 실행합니다.
* 리다이렉트 라우트인 경우 자동으로 리다이렉트합니다.
*/
resolve(): void {
const pathname = window.location.pathname;
const match = this.router.match(pathname);
// 리다이렉트 라우트인 경우 처리
if (match && match.route.redirect) {
logger.log(`Redirecting from ${pathname} to ${match.route.redirect}`);
this.navigate(match.route.redirect);
return;
}
if (this.onRouteChange) {
this.onRouteChange(match);
}
}
/**
* window.history.pushState()를 사용하여 프로그래매틱 네비게이션을 수행합니다.
*
* @param path - 이동할 경로
* @param state - history state 객체 (선택사항)
*/
navigate(path: string, state?: unknown): void {
window.history.pushState(state ?? null, '', path);
this.resolve();
}
/**
* RouteResolver를 정리합니다.
*
* - popstate 이벤트 리스너를 제거합니다.
*/
destroy(): void {
window.removeEventListener('popstate', this.handlePopState);
this.onRouteChange = null;
this.isInitialized = false;
}
}
+358
View File
@@ -0,0 +1,358 @@
import { AuthManager } from '../auth/AuthManager';
import { createLogger } from '../utils/Logger';
const logger = createLogger('Router');
/**
* 라우트 메타 정보
*/
export interface RouteMeta {
title?: string;
[key: string]: unknown;
}
/**
* 인증 타입
*/
export type AuthType = 'admin' | 'user';
/**
* 라우트 인터페이스
*/
export interface Route {
path: string;
layout?: string;
redirect?: string;
endpoint?: string;
params?: Record<string, string>;
/** 쿼리 파라미터 (배열 쿼리 파라미터 지원: key[]=[...]) */
query?: Record<string, string | string[]>;
auth_required?: boolean;
auth_type?: AuthType;
meta?: RouteMeta;
}
/**
* 라우트 매칭 결과
*/
export interface RouteMatch {
route: Route;
params: Record<string, string>;
}
/**
* 이벤트 핸들러 타입
*/
type EventHandler = (...args: any[]) => void;
/**
* Router 클래스
*
* URL 패턴 매칭과 동적 파라미터 추출을 담당합니다.
*/
export class Router {
private routes: Route[] = [];
private templateIdentifier: string;
private eventHandlers: Map<string, EventHandler[]> = new Map();
private pendingNavigation: string | null = null;
private isNavigating: boolean = false;
constructor(templateIdentifier: string) {
this.templateIdentifier = templateIdentifier;
this.initPopstateListener();
}
/**
* 브라우저 뒤로가기/앞으로가기 이벤트 리스너 초기화
*/
private initPopstateListener(): void {
window.addEventListener('popstate', this.handlePopState);
}
/**
* popstate 이벤트 핸들러 (화살표 함수로 this 바인딩 유지)
*/
private handlePopState = (): void => {
this.navigateToCurrentPath();
};
/**
* 이벤트 핸들러 등록
*/
on(event: string, handler: EventHandler): void {
if (!this.eventHandlers.has(event)) {
this.eventHandlers.set(event, []);
}
this.eventHandlers.get(event)!.push(handler);
}
/**
* 이벤트 발생 (async 핸들러 지원)
*/
private async emit(event: string, ...args: any[]): Promise<void> {
const handlers = this.eventHandlers.get(event);
if (handlers) {
// 모든 핸들러가 완료될 때까지 대기 (async 핸들러 지원)
await Promise.all(handlers.map(handler => handler(...args)));
}
}
/**
* API에서 라우트 목록을 로드합니다.
*/
async loadRoutes(): Promise<void> {
try {
const response = await fetch(`/api/templates/${this.templateIdentifier}/routes.json`);
if (!response.ok) {
throw new Error(`Failed to load routes: ${response.statusText}`);
}
const result = await response.json();
if (!result.success) {
throw new Error('Failed to load routes from API');
}
// API 응답 형태: { success: true, data: { version: "1.0.0", routes: [...] } }
if (result.data && Array.isArray(result.data.routes)) {
this.routes = result.data.routes;
logger.log(`Loaded ${this.routes.length} routes`);
} else {
throw new Error('Invalid routes data format');
}
} catch (error) {
logger.error('Error loading routes:', error);
throw error;
}
}
/**
* 라우트 목록을 직접 설정합니다 (병렬 로딩용).
*
* @param routes - 설정할 라우트 배열
*/
setRoutes(routes: Route[]): void {
this.routes = routes;
logger.log(`Set ${this.routes.length} routes`);
}
/**
* 현재 경로와 매칭되는 라우트를 찾습니다.
*
* @param pathname - 매칭할 URL 경로
* @returns 매칭된 라우트와 파라미터, 없으면 null
*/
match(pathname: string): RouteMatch | null {
for (const route of this.routes) {
const params = this.matchPattern(route.path, pathname);
if (params !== null) {
return {
route,
params,
};
}
}
return null;
}
/**
* 패턴과 경로를 매칭하고 파라미터를 추출합니다.
*
* 지원되는 패턴:
* - /admin - 정확한 매칭
* - /admin/users/:id - 동적 파라미터 (:id)
* - * /admin - 언어 prefix 지원 (/admin, /ko/admin, /en/admin)
*
* @param pattern - 라우트 패턴
* @param pathname - 실제 URL 경로
* @returns 추출된 파라미터 객체, 매칭 실패 시 null
*/
private matchPattern(pattern: string, pathname: string): Record<string, string> | null {
// 파라미터 이름 추출
const paramNames: string[] = [];
// 패턴을 정규식으로 변환
let regexPattern = pattern
// :id 형태의 동적 파라미터를 캡처 그룹으로 변환
.replace(/:([^/]+)/g, (_, paramName) => {
paramNames.push(paramName);
return '([^/]+)';
});
// 패턴 시작의 */를 optional 언어 prefix로 변환 (예: /ko, /en)
// */admin → /admin 또는 /ko/admin 또는 /en/admin
if (regexPattern.startsWith('*/')) {
regexPattern = '(?:/[^/]+)?' + regexPattern.slice(1);
}
// 특수 문자 이스케이프
regexPattern = regexPattern.replace(/\//g, '\\/');
// 정규식 생성 (전체 문자열 매칭)
const regex = new RegExp(`^${regexPattern}$`);
const match = pathname.match(regex);
if (!match) {
return null;
}
// 파라미터 추출
const params: Record<string, string> = {};
paramNames.forEach((name, index) => {
params[name] = match[index + 1];
});
return params;
}
/**
* 현재 로드된 라우트 목록을 반환합니다.
*/
getRoutes(): Route[] {
return [...this.routes];
}
/**
* 경로 기반 인증 타입 판단
*
* @param route - 라우트 정보
* @param pathname - URL 경로
* @returns 인증 타입
*/
private getAuthType(route: Route, pathname: string): AuthType {
// 1. 라우트에 명시된 경우 사용
if (route.auth_type) {
return route.auth_type;
}
// 2. 경로 기반 자동 판단
if (pathname.startsWith('/admin')) {
return 'admin';
}
return 'user';
}
/**
* 현재 URL 경로를 처리하여 매칭되는 라우트를 찾고 이벤트를 발생시킵니다.
*/
async navigateToCurrentPath(): Promise<void> {
const pathname = window.location.pathname;
const search = window.location.search;
const matchResult = this.match(pathname);
if (!matchResult) {
logger.warn(`No route matched for path: ${pathname}`);
this.emit('routeNotFound', pathname);
return;
}
// 리다이렉트 라우트인 경우 처리
if (matchResult.route.redirect) {
logger.log(`Redirecting from ${pathname} to ${matchResult.route.redirect}`);
this.navigate(matchResult.route.redirect);
return;
}
// 인증 검증
if (matchResult.route.auth_required) {
const authType = this.getAuthType(matchResult.route, pathname);
const authManager = AuthManager.getInstance();
// 이미 인증 상태가 확인된 경우 API 호출 스킵
let isAuthenticated = authManager.isAuthenticated() && authManager.getAuthType() === authType;
// 인증 상태가 없거나 타입이 다른 경우에만 API 호출
if (!isAuthenticated) {
isAuthenticated = await authManager.checkAuth(authType);
}
if (!isAuthenticated) {
const loginUrl = authManager.getLoginRedirectUrl(authType, pathname + search);
logger.log(`Not authenticated, redirecting to: ${loginUrl}`);
window.location.href = loginUrl;
return;
}
}
// query 파라미터 파싱 (배열 쿼리 파라미터 지원)
const queryParams = new URLSearchParams(search);
const query: Record<string, string | string[]> = {};
// 모든 키를 순회하며 배열 값 처리
for (const key of queryParams.keys()) {
// 이미 처리된 키는 스킵
if (key in query) continue;
const values = queryParams.getAll(key);
if (values.length > 1) {
// 여러 값이 있으면 배열로 저장
query[key] = values;
} else if (values.length === 1) {
// key[]로 끝나면 단일 값도 배열로 저장 (일관성 유지)
if (key.endsWith('[]')) {
query[key] = values;
} else {
query[key] = values[0];
}
}
}
// 라우트 변경 이벤트 발생 (핸들러가 완료될 때까지 대기)
await this.emit('routeChange', {
path: pathname,
layout: matchResult.route.layout,
endpoint: matchResult.route.endpoint,
params: { ...(matchResult.route.params || {}), ...matchResult.params },
query,
auth_required: matchResult.route.auth_required,
auth_type: matchResult.route.auth_type,
meta: matchResult.route.meta,
});
}
/**
* 지정된 경로로 이동합니다.
*
* 동시에 여러 navigate 호출이 발생할 경우, 마지막 요청만 처리합니다.
* 이전 navigate가 진행 중이면 대기했다가 최신 경로로 이동합니다.
*
* @param path - 이동할 경로 (예: '/admin/dashboard')
*/
navigate(path: string): void {
// 이미 navigate가 진행 중이면 대기열에 추가
if (this.isNavigating) {
this.pendingNavigation = path;
return;
}
this.executeNavigation(path);
}
/**
* 실제 navigate 실행
*/
private async executeNavigation(path: string): Promise<void> {
this.isNavigating = true;
this.pendingNavigation = null;
try {
// URL 변경 (브라우저 히스토리에 추가)
window.history.pushState({}, '', path);
// 라우트 매칭 및 렌더링 (완료까지 대기)
await this.navigateToCurrentPath();
} finally {
this.isNavigating = false;
// 대기 중인 navigate가 있으면 실행
if (this.pendingNavigation) {
const nextPath = this.pendingNavigation;
this.executeNavigation(nextPath);
}
}
}
}
@@ -0,0 +1,225 @@
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { Router } from '../Router';
import { RouteResolver } from '../RouteResolver';
import { Logger } from '../../utils/Logger';
// fetch 모킹
global.fetch = vi.fn();
describe('RouteResolver', () => {
let router: Router;
let resolver: RouteResolver;
let mockCallback: ReturnType<typeof vi.fn>;
beforeEach(() => {
router = new Router('sirsoft-admin_basic');
resolver = new RouteResolver(router);
mockCallback = vi.fn();
vi.clearAllMocks();
// Logger 디버그 모드 활성화
Logger.getInstance().setDebug(true);
// 기본 라우트 목록 모킹
// API 응답 형태: { success: true, data: { version: "1.0.0", routes: [...] } }
(global.fetch as any).mockResolvedValue({
ok: true,
json: async () => ({
success: true,
data: {
version: '1.0.0',
routes: [
{ path: '/admin', layout: 'dashboard' },
{ path: '/admin/users/:id', layout: 'user-detail' },
],
},
}),
});
});
afterEach(() => {
resolver.destroy();
// Logger 디버그 모드 비활성화
Logger.getInstance().setDebug(false);
});
describe('init', () => {
it('router.loadRoutes()를 호출해야 합니다', async () => {
const loadRoutesSpy = vi.spyOn(router, 'loadRoutes');
await resolver.init(mockCallback);
expect(loadRoutesSpy).toHaveBeenCalledOnce();
});
it('popstate 이벤트 리스너를 등록해야 합니다', async () => {
const addEventListenerSpy = vi.spyOn(window, 'addEventListener');
await resolver.init(mockCallback);
expect(addEventListenerSpy).toHaveBeenCalledWith('popstate', expect.any(Function));
});
it('초기 라우트를 해석하고 콜백을 호출해야 합니다', async () => {
// 현재 경로를 /admin으로 설정
Object.defineProperty(window, 'location', {
value: { pathname: '/admin' },
writable: true,
});
await resolver.init(mockCallback);
expect(mockCallback).toHaveBeenCalledOnce();
expect(mockCallback).toHaveBeenCalledWith(
expect.objectContaining({
route: expect.objectContaining({ layout: 'dashboard' }),
params: {},
})
);
});
it('이미 초기화된 경우 경고를 출력하고 재초기화하지 않아야 합니다', async () => {
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
await resolver.init(mockCallback);
await resolver.init(mockCallback);
expect(consoleWarnSpy).toHaveBeenCalledWith('[RouteResolver]', 'RouteResolver is already initialized');
expect(mockCallback).toHaveBeenCalledOnce(); // 첫 번째 init만 콜백 호출
});
});
describe('resolve', () => {
beforeEach(async () => {
await resolver.init(mockCallback);
mockCallback.mockClear(); // init에서 호출된 것 제외
});
it('현재 경로와 매칭되는 라우트를 찾아 콜백을 호출해야 합니다', () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/users/123' },
writable: true,
});
resolver.resolve();
expect(mockCallback).toHaveBeenCalledOnce();
expect(mockCallback).toHaveBeenCalledWith(
expect.objectContaining({
route: expect.objectContaining({ layout: 'user-detail' }),
params: { id: '123' },
})
);
});
it('매칭되지 않는 경로는 null로 콜백을 호출해야 합니다', () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/unknown' },
writable: true,
});
resolver.resolve();
expect(mockCallback).toHaveBeenCalledOnce();
expect(mockCallback).toHaveBeenCalledWith(null);
});
});
describe('navigate', () => {
beforeEach(async () => {
await resolver.init(mockCallback);
mockCallback.mockClear();
});
it('window.history.pushState()를 호출해야 합니다', () => {
const pushStateSpy = vi.spyOn(window.history, 'pushState');
resolver.navigate('/admin/users/456');
expect(pushStateSpy).toHaveBeenCalledOnce();
expect(pushStateSpy).toHaveBeenCalledWith(null, '', '/admin/users/456');
});
it('state를 전달하면 pushState에 포함되어야 합니다', () => {
const pushStateSpy = vi.spyOn(window.history, 'pushState');
const state = { fromSearch: true };
resolver.navigate('/admin/users/456', state);
expect(pushStateSpy).toHaveBeenCalledWith(state, '', '/admin/users/456');
});
it('navigate 후 resolve()를 호출하여 콜백이 실행되어야 합니다', () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/users/456' },
writable: true,
});
resolver.navigate('/admin/users/456');
expect(mockCallback).toHaveBeenCalledOnce();
expect(mockCallback).toHaveBeenCalledWith(
expect.objectContaining({
route: expect.objectContaining({ layout: 'user-detail' }),
params: { id: '456' },
})
);
});
});
describe('popstate 이벤트 처리', () => {
beforeEach(async () => {
await resolver.init(mockCallback);
mockCallback.mockClear();
});
it('popstate 이벤트 발생 시 resolve()가 호출되어야 합니다', () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin' },
writable: true,
});
window.dispatchEvent(new PopStateEvent('popstate'));
expect(mockCallback).toHaveBeenCalledOnce();
expect(mockCallback).toHaveBeenCalledWith(
expect.objectContaining({
route: expect.objectContaining({ layout: 'dashboard' }),
params: {},
})
);
});
});
describe('destroy', () => {
it('popstate 이벤트 리스너를 제거해야 합니다', async () => {
const removeEventListenerSpy = vi.spyOn(window, 'removeEventListener');
await resolver.init(mockCallback);
resolver.destroy();
expect(removeEventListenerSpy).toHaveBeenCalledWith('popstate', expect.any(Function));
});
it('destroy 후 popstate 이벤트가 발생해도 콜백이 호출되지 않아야 합니다', async () => {
await resolver.init(mockCallback);
mockCallback.mockClear();
resolver.destroy();
window.dispatchEvent(new PopStateEvent('popstate'));
expect(mockCallback).not.toHaveBeenCalled();
});
it('destroy 후 isInitialized가 false로 설정되어야 합니다', async () => {
await resolver.init(mockCallback);
resolver.destroy();
// 다시 init 호출 시 경고 없이 초기화되어야 함
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
await resolver.init(mockCallback);
expect(consoleWarnSpy).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,556 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { Router } from '../Router';
import { AuthManager } from '../../auth/AuthManager';
// fetch 모킹
global.fetch = vi.fn();
// AuthManager 모킹
vi.mock('../../auth/AuthManager', () => ({
AuthManager: {
getInstance: vi.fn(),
},
}));
describe('Router', () => {
let router: Router;
beforeEach(() => {
router = new Router('sirsoft-admin_basic');
vi.clearAllMocks();
});
describe('loadRoutes', () => {
it('API에서 라우트 목록을 성공적으로 로드해야 합니다', async () => {
const mockRoutes = [
{ path: '/admin', layout: 'dashboard' },
{ path: '/admin/users/:id', layout: 'user-detail' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
expect(global.fetch).toHaveBeenCalledWith('/api/templates/sirsoft-admin_basic/routes.json');
expect(router.getRoutes()).toEqual(mockRoutes);
});
it('API 호출 실패 시 에러를 던져야 합니다', async () => {
(global.fetch as any).mockResolvedValueOnce({
ok: false,
statusText: 'Not Found',
});
await expect(router.loadRoutes()).rejects.toThrow('Failed to load routes: Not Found');
});
it('success가 false일 때 에러를 던져야 합니다', async () => {
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: false,
data: null,
}),
});
await expect(router.loadRoutes()).rejects.toThrow('Failed to load routes from API');
});
it('잘못된 데이터 형식 시 에러를 던져야 합니다', async () => {
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0' }, // routes 배열이 없음
}),
});
await expect(router.loadRoutes()).rejects.toThrow('Invalid routes data format');
});
});
describe('match', () => {
beforeEach(async () => {
const mockRoutes = [
{ path: '/admin', layout: 'dashboard' },
{ path: '/admin/users', layout: 'user-list' },
{ path: '/admin/users/:id', layout: 'user-detail' },
{ path: '/admin/files/*', layout: 'file-browser' },
{ path: '/admin/posts/:postId/comments/:commentId', layout: 'comment-detail' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
});
it('정확한 경로 매칭을 수행해야 합니다', () => {
const result = router.match('/admin');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('dashboard');
expect(result?.params).toEqual({});
});
it('동적 파라미터를 추출해야 합니다', () => {
const result = router.match('/admin/users/123');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('user-detail');
expect(result?.params).toEqual({ id: '123' });
});
it('다중 동적 파라미터를 추출해야 합니다', () => {
const result = router.match('/admin/posts/456/comments/789');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('comment-detail');
expect(result?.params).toEqual({
postId: '456',
commentId: '789',
});
});
// TODO: 와일드카드 패턴(*)은 아직 미구현 - 현재는 */만 언어 prefix용으로 지원
it.skip('와일드카드 패턴을 매칭해야 합니다', () => {
const result = router.match('/admin/files/documents/2024/report.pdf');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('file-browser');
expect(result?.params).toEqual({});
});
it('매칭되지 않는 경로는 null을 반환해야 합니다', () => {
const result = router.match('/unknown/path');
expect(result).toBeNull();
});
it('부분 매칭은 수행하지 않아야 합니다', () => {
const result = router.match('/admin/users/123/extra');
expect(result).toBeNull();
});
it('첫 번째로 매칭되는 라우트를 반환해야 합니다', () => {
// /admin/users는 /admin/users와 /admin/users/:id 둘 다 매칭 가능
// 하지만 정확히 매칭되는 /admin/users를 먼저 반환해야 함
const result = router.match('/admin/users');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('user-list');
expect(result?.params).toEqual({});
});
});
describe('matchPattern (간접 테스트)', () => {
beforeEach(async () => {
const mockRoutes = [
{ path: '/test/:param', layout: 'test' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
});
it('영숫자와 하이픈, 언더스코어를 포함한 파라미터를 추출해야 합니다', () => {
const result = router.match('/test/user-id_123');
expect(result).not.toBeNull();
expect(result?.params.param).toBe('user-id_123');
});
it('슬래시가 포함된 파라미터는 매칭하지 않아야 합니다', () => {
const result = router.match('/test/invalid/path');
expect(result).toBeNull();
});
});
describe('getRoutes', () => {
it('로드된 라우트 목록의 복사본을 반환해야 합니다', async () => {
const mockRoutes = [
{ path: '/admin', layout: 'dashboard' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
const routes = router.getRoutes();
routes.push({ path: '/test', layout: 'test' });
// 원본은 변경되지 않아야 함
expect(router.getRoutes().length).toBe(1);
});
});
describe('redirect', () => {
beforeEach(async () => {
const mockRoutes = [
{ path: '/admin', redirect: '/admin/dashboard', auth_required: true },
{ path: '/admin/login', layout: 'admin_login', auth_required: false },
{ path: '/admin/dashboard', layout: 'admin_dashboard', auth_required: true },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
});
it('리다이렉트 라우트를 매칭해야 합니다', () => {
const result = router.match('/admin');
expect(result).not.toBeNull();
expect(result?.route.redirect).toBe('/admin/dashboard');
expect(result?.route.auth_required).toBe(true);
});
it('일반 라우트는 layout을 가져야 합니다', () => {
const result = router.match('/admin/dashboard');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('admin_dashboard');
expect(result?.route.redirect).toBeUndefined();
});
it('navigateToCurrentPath에서 리다이렉트 라우트를 처리해야 합니다', async () => {
// 리다이렉트 후 pathname이 변경되도록 시뮬레이션
let currentPathname = '/admin';
Object.defineProperty(window, 'location', {
get: () => ({ pathname: currentPathname, search: '', href: '' }),
configurable: true,
});
// window.history.pushState 모킹 - pathname도 함께 변경
const pushStateSpy = vi.spyOn(window.history, 'pushState').mockImplementation((_, __, url) => {
currentPathname = url as string;
});
// Mock AuthManager for auth_required routes
const mockAuthManager = {
isAuthenticated: vi.fn().mockReturnValue(false),
getAuthType: vi.fn().mockReturnValue(null),
checkAuth: vi.fn().mockResolvedValue(true),
getLoginRedirectUrl: vi.fn(),
};
(AuthManager.getInstance as any).mockReturnValue(mockAuthManager);
// routeChange 이벤트 리스너
const routeChangeHandler = vi.fn();
router.on('routeChange', routeChangeHandler);
// navigateToCurrentPath 호출 (async)
await router.navigateToCurrentPath();
// pushState가 리다이렉트 경로로 호출되어야 함
expect(pushStateSpy).toHaveBeenCalledWith({}, '', '/admin/dashboard');
// 최종적으로 routeChange가 dashboard 레이아웃으로 호출되어야 함
expect(routeChangeHandler).toHaveBeenCalledWith(
expect.objectContaining({
layout: 'admin_dashboard',
})
);
pushStateSpy.mockRestore();
});
});
describe('인증 가드', () => {
let mockAuthManager: any;
beforeEach(async () => {
const mockRoutes = [
{ path: '/admin/login', layout: 'admin_login', auth_required: false },
{ path: '/admin/dashboard', layout: 'admin_dashboard', auth_required: true },
{ path: '/admin/users', layout: 'admin_users', auth_required: true, auth_type: 'admin' as const },
{ path: '/profile', layout: 'user_profile', auth_required: true },
{ path: '/login', layout: 'user_login', auth_required: false },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
// Mock AuthManager
mockAuthManager = {
isAuthenticated: vi.fn().mockReturnValue(false),
getAuthType: vi.fn().mockReturnValue(null),
checkAuth: vi.fn(),
getLoginRedirectUrl: vi.fn(),
};
(AuthManager.getInstance as any).mockReturnValue(mockAuthManager);
});
afterEach(() => {
vi.clearAllMocks();
});
it('auth_required가 true이고 미인증 시 로그인 페이지로 리다이렉트해야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/dashboard', search: '', href: '' },
writable: true,
configurable: true,
});
mockAuthManager.checkAuth.mockResolvedValue(false);
mockAuthManager.getLoginRedirectUrl.mockReturnValue('/admin/login?redirect=%2Fadmin%2Fdashboard');
const routeChangeHandler = vi.fn();
router.on('routeChange', routeChangeHandler);
await router.navigateToCurrentPath();
expect(mockAuthManager.checkAuth).toHaveBeenCalledWith('admin');
expect(window.location.href).toBe('/admin/login?redirect=%2Fadmin%2Fdashboard');
expect(routeChangeHandler).not.toHaveBeenCalled();
});
it('auth_required가 true이고 인증됨 시 정상 렌더링해야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/dashboard', search: '', href: '' },
writable: true,
configurable: true,
});
mockAuthManager.checkAuth.mockResolvedValue(true);
const routeChangeHandler = vi.fn();
router.on('routeChange', routeChangeHandler);
await router.navigateToCurrentPath();
expect(mockAuthManager.checkAuth).toHaveBeenCalledWith('admin');
expect(routeChangeHandler).toHaveBeenCalledWith(
expect.objectContaining({
layout: 'admin_dashboard',
})
);
});
it('/admin 경로는 관리자 로그인 페이지로 리다이렉트해야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/users', search: '', href: '' },
writable: true,
configurable: true,
});
mockAuthManager.checkAuth.mockResolvedValue(false);
mockAuthManager.getLoginRedirectUrl.mockReturnValue('/admin/login?redirect=%2Fadmin%2Fusers');
await router.navigateToCurrentPath();
expect(mockAuthManager.checkAuth).toHaveBeenCalledWith('admin');
expect(mockAuthManager.getLoginRedirectUrl).toHaveBeenCalledWith('admin', '/admin/users');
});
it('일반 경로는 사용자 로그인 페이지로 리다이렉트해야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/profile', search: '', href: '' },
writable: true,
configurable: true,
});
mockAuthManager.checkAuth.mockResolvedValue(false);
mockAuthManager.getLoginRedirectUrl.mockReturnValue('/login?redirect=%2Fprofile');
await router.navigateToCurrentPath();
expect(mockAuthManager.checkAuth).toHaveBeenCalledWith('user');
expect(mockAuthManager.getLoginRedirectUrl).toHaveBeenCalledWith('user', '/profile');
});
it('auth_required가 false인 경우 인증 검증을 수행하지 않아야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/login', search: '', href: '' },
writable: true,
configurable: true,
});
const routeChangeHandler = vi.fn();
router.on('routeChange', routeChangeHandler);
await router.navigateToCurrentPath();
expect(mockAuthManager.checkAuth).not.toHaveBeenCalled();
expect(routeChangeHandler).toHaveBeenCalledWith(
expect.objectContaining({
layout: 'admin_login',
})
);
});
it('라우트에 auth_type이 명시된 경우 해당 타입을 사용해야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/users', search: '', href: '' },
writable: true,
configurable: true,
});
mockAuthManager.checkAuth.mockResolvedValue(true);
await router.navigateToCurrentPath();
// auth_type이 'admin'으로 명시되어 있으므로 'admin'으로 호출
expect(mockAuthManager.checkAuth).toHaveBeenCalledWith('admin');
});
});
describe('배열 쿼리 파라미터 파싱', () => {
it('같은 키의 여러 값을 배열로 파싱해야 합니다', async () => {
const mockRoutes = [
{ path: '/admin/products', layout: 'products' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
let capturedRoute: any = null;
router.on('routeChange', (route: any) => {
capturedRoute = route;
});
// 배열 쿼리 파라미터가 있는 URL 설정
Object.defineProperty(window, 'location', {
value: {
pathname: '/admin/products',
search: '?sales_status[]=on_sale&sales_status[]=sold_out&page=1',
href: '',
},
writable: true,
configurable: true,
});
await router.navigateToCurrentPath();
// query에서 배열이 올바르게 파싱되었는지 확인
expect(capturedRoute).not.toBeNull();
expect(capturedRoute.query['sales_status[]']).toEqual(['on_sale', 'sold_out']);
expect(capturedRoute.query['page']).toBe('1');
});
it('단일 배열 값도 배열로 파싱해야 합니다 (key[] 형태)', async () => {
const mockRoutes = [
{ path: '/admin/products', layout: 'products' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
let capturedRoute: any = null;
router.on('routeChange', (route: any) => {
capturedRoute = route;
});
// 단일 배열 값이 있는 URL 설정
Object.defineProperty(window, 'location', {
value: {
pathname: '/admin/products',
search: '?sales_status[]=on_sale',
href: '',
},
writable: true,
configurable: true,
});
await router.navigateToCurrentPath();
// key[]로 끝나는 단일 값도 배열로 파싱되어야 함
expect(capturedRoute).not.toBeNull();
expect(capturedRoute.query['sales_status[]']).toEqual(['on_sale']);
});
it('일반 파라미터는 문자열로 유지해야 합니다', async () => {
const mockRoutes = [
{ path: '/admin/products', layout: 'products' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
let capturedRoute: any = null;
router.on('routeChange', (route: any) => {
capturedRoute = route;
});
Object.defineProperty(window, 'location', {
value: {
pathname: '/admin/products',
search: '?page=1&search=test',
href: '',
},
writable: true,
configurable: true,
});
await router.navigateToCurrentPath();
// 일반 파라미터는 문자열
expect(capturedRoute).not.toBeNull();
expect(capturedRoute.query['page']).toBe('1');
expect(capturedRoute.query['search']).toBe('test');
expect(typeof capturedRoute.query['page']).toBe('string');
});
});
});
+8
View File
@@ -0,0 +1,8 @@
/**
* Routing 모듈
*
* Router와 RouteResolver를 외부에서 사용할 수 있도록 export합니다.
*/
export { Router, Route, RouteMatch } from './Router';
export { RouteResolver, RouteChangeCallback } from './RouteResolver';