NavigateTo with UrlBuilder

Date: 2022-09-06

Extendable navigateTo function with auto-complete, without a large INavigator interface
Prevents a lot of ‘imports’ and parameter replacing in components

export interface INavigator {
    navigateTo(fn: (u: UrlBuilder) => string): void;
    reload(): void;
    navigateToUrl(url: string, params?: any): void;
}

export class UrlBuilder {
    home() { return AppRoutes.home }
    purchaseContracts() { return AppRoutes.purchaseContracts }
    stockList() { return AppRoutes.stockList }
    planningList() { return AppRoutes.planningList }
    planningDetail(id: string) { return replaceAppRoutesParams(AppRoutes.planningDetail, id); }
    purchaseContractsEdit(id: string) { return replaceAppRoutesParams(AppRoutes.purchaseContractsEdit, id); }
    tracingDetail(type: string, id: string) { return replaceAppRoutesParams(AppRoutes.tracingDetail, type, id); }
    stockSortDetail(productId: string, purchaseContractLineId: string, stockType: string) { return replaceAppRoutesParams(AppRoutes.stockSortDetail, productId, purchaseContractLineId, stockType); }
    purchaseContractLine(id: string) { return replaceAppRoutesParams(AppRoutes.purchaseContractLine, id); }
}

export function replaceAppRoutesParams(route: AppRoutes, ...params: string[]) {
    const path = String(route);
    let i = 0;
    const getParam = () => {
        const param = params[i];
        i += 1;
        return param;
    };
    return path.replaceAll(/(:[^/]+)/g, getParam);
}

export enum AppRoutes {
    home = "/home",
    purchaseContracts = "/purchase-contracts",
    stockList = "/stock",
    planningList = "/planning",
    planningDetail = "/planning/:id",
    purchaseContractsEdit = "/purchase-contracts/:id",
    tracingDetail = "/tracing/:type/:id",
    stockSortDetail = "/stock-sort/:productId/:purchaseContractLineId/:stockType",
    purchaseContractLine = "/purchase-contract-line/:id"
}

// Usage:
appDomain.INavigator.navigateTo(x => x.tracingDetail(TracingType.purchase, purchaseContract.id));


66830cookie-checkNavigateTo with UrlBuilder