graycoreio/daffodil

View on GitHub
libs/external-router/src/router/strategies/insert-route-before-wildcard.ts

Summary

Maintainability
A
0 mins
Test Coverage
import {
  Route,
  Routes,
} from '@angular/router';

import { DaffExternalRouterNoWildcardError } from '../../errors/no-wildcard';
import { DaffExternalRouterInsertionStrategy } from '../../model/insertion-strategy.type';

/**
 * Inserts a Route into Routes right before the wildcard route.
 * If no wildcard is found, it fails fast with a `DaffExternalRouterNoWildcardError`.
 */
export const daffInsertRouteBeforeWildCardStrategy: DaffExternalRouterInsertionStrategy = (
  route: Route,
  routes: Routes,
): Routes => {
  const index = routes.findIndex((r: Route) => r.path === '**');
  if (index === -1) {
    throw new DaffExternalRouterNoWildcardError(
      'No wildcard (**) route was found during route resolution.',
    );
  }
  return [
    ...routes.slice(0, index),
    route,
    ...routes.slice(index),
  ];
};