All files / app/services list-guard.ts

32% Statements 8/25
29.41% Branches 5/17
50% Functions 1/2
22.72% Lines 5/22

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 44 45 46 47 48 49 50 51 52 53                  1x   1x 1x 1x 1x                                                                            
import { ShoppingListDataService } from './shopping-list-data.service';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { PowerSyncService } from './powersync';
import { DefaultList } from './default-list';
 
@Injectable({
  providedIn: 'root',
})
export class ListGuard {
  constructor(
    private shoppingListService: ShoppingListDataService,
    private powerSync: PowerSyncService,
    private defaultList: DefaultList,
    private router: Router
  ) {}
 
  async canActivate(next: ActivatedRouteSnapshot, _state: RouterStateSnapshot): Promise<boolean | UrlTree> {
    const listId = next.queryParams['listId'];
 
    // Bypass list verification for Cypress E2E tests
    if (typeof window !== 'undefined' && 'Cypress' in window) {
      if (!listId) {
        return this.router.createUrlTree(['/list'], { queryParams: { listId: '1234567890' } });
      }
      return true;
    }
 
    if (!listId) {
      const defaultListId = this.defaultList.getDefaultList();
 
      if (defaultListId === null) {
        return this.router.createUrlTree(['/lists']);
      }
 
      return this.router.createUrlTree(['/list'], { queryParams: { listId: defaultListId.toString() } });
    }
 
    await this.powerSync.waitForPowerSyncReady();
    let listIdBig: bigint;
    try {
      listIdBig = BigInt(listId);
    } catch {
      return this.router.createUrlTree([`/not-found?liste=${listId}`]);
    }
 
    if (!await this.shoppingListService.listExists(listIdBig)) {
      return this.router.createUrlTree([`/not-found?liste=${listId}`]);
    }
    return true;
  }
}