import { Dictionary } from "@types"; import { PageID, TabID } from "pages"; import { get, isArray, isString, replace } from "lodash"; type PathKey = [PageID, TabID?] | PageID; const makePathKey = (arg: PathKey): string => { if (isArray(arg)) { const tabStr = arg[1] !== undefined ? "/" + String(arg[1]) : ""; return String(arg[0]) + tabStr; } else { return String(arg); } }; const getPageId = (key: PathKey): PageID => { if (isArray(key)) { return key[0]; } else { return key; } }; const getTabId = (key: PathKey): TabID => { if (isArray(key)) { return key[1] ?? TabID.NONE; } else { return TabID.NONE; } }; const PATHS_DASHBOARD = { [makePathKey(PageID.DASHBOARD_ENPTY)]: "/dashboard/loading", [makePathKey(PageID.DASHBOARD_OVERVIEW)]: "/dashboard", [makePathKey(PageID.ログインユーザ_顧客一覧)]: "/dashboard/login-user/customer/list", [makePathKey(PageID.ログインユーザ_顧客新規登録)]: "/dashboard/login-user/customer/register", [makePathKey(PageID.ログインユーザ_店舗一覧)]: "/dashboard/login-user/shop/list", [makePathKey(PageID.サービス券発行用QRコード)]: "/dashboard/qrcode/generate", [makePathKey(PageID.サービス券利用履歴)]: "/dashboard/qrcode/history", }; const PATHS = { [makePathKey(PageID.NONE)]: "/", // 認証 [makePathKey(PageID.LOGIN)]: "/login", [makePathKey(PageID.LOGOUT)]: "/logout", [makePathKey(PageID.QRサービス券発行申請)]: "qr-service/acquitision/:token", // ダッシュボード---------------- ...PATHS_DASHBOARD, // その他 [makePathKey(PageID.PAGE_403)]: "403", [makePathKey(PageID.PAGE_404)]: "404", }; export type PathOption = { page?: number; query?: Dictionary; }; export function getPath(key: PathKey, option?: PathOption) { const pageId = getPageId(key); const tabId = getTabId(key); let path = getRoute(pageId); // ページ番号解決 path = replacePathParam(path, "page", option?.page ?? 0); // その他URLパラメータ変換 if (option?.query !== undefined) { Object.keys(option.query).forEach((key) => { const value = get(option.query, key); if (value === undefined) return; path = replacePathParam(path, key, value); }); } return path; } export function getListPagePath(key: PathKey, page: number): string { return getPath(key, { page }); } export function getRoute(key: PathKey, exclude?: string): string { let path = get(PATHS, makePathKey(key)); if (!path) throw new Error("ルート未定義:" + makePathKey(key)); if (exclude) { path = replace(path, "/" + exclude + "/", ""); } return path; } function replacePathParam( sourceStr: string, searchStr: string, replacement: string | number ): string { return replace( sourceStr, ":" + searchStr, isString(replacement) ? replacement : String(replacement) ); }