All files / src/app/core/routing pwa-url.serializer.ts

100% Statements 14/14
100% Branches 0/0
100% Functions 7/7
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 442x     222x 128x   111x             111x 111x 111x 111x 111x               2x 14x     13x 13x       111x                  
import { DefaultUrlSerializer, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree } from '@angular/router';
 
function removeMatrixParametersFromGroup(group: UrlSegmentGroup): UrlSegmentGroup {
  return new UrlSegmentGroup(
    group.segments.map(segment => new UrlSegment(segment.path, {})),
    Object.entries(group.children).reduce(
      (acc, [key, group]) => ({ ...acc, [key]: removeMatrixParametersFromGroup(group) }),
      {}
    )
  );
}
 
function removeMatrixParameters(tree: UrlTree): UrlTree {
  const newTree = new UrlTree();
  newTree.root = removeMatrixParametersFromGroup(tree.root);
  newTree.fragment = tree.fragment;
  newTree.queryParams = tree.queryParams;
  return newTree;
}
 
/**
 * Custom serializer for allowing parenthesis in URLs and removing matrix parameters
 *
 * taken from: https://github.com/angular/angular/issues/10280#issuecomment-309129784
 */
export class PWAUrlSerializer implements UrlSerializer {
  private defaultUrlSerializer: DefaultUrlSerializer = new DefaultUrlSerializer();
 
  parse(url: string): UrlTree {
    const newUrl = url.replace(/\(/g, '%28').replace(/\)/g, '%29');
    return this.defaultUrlSerializer.parse(newUrl);
  }
 
  serialize(tree: UrlTree): string {
    return (
      this.defaultUrlSerializer
        .serialize(removeMatrixParameters(tree))
        // display parenthesis unencoded in URL
        .replace(/%28/g, '(')
        .replace(/%29/g, ')')
    );
  }
}