All files / src/app/core/services locale.service.ts

82.65% Statements 81/98
70% Branches 21/30
78.37% Functions 29/37
96.61% Lines 57/59

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 13416x 16x 16x 16x 16x 16x 16x 16x 16x         16x   18x 10x 10x 10x 10x 10x   10x       4x 4x     4x           2x 2x         3x   3x 2x     2x   2x             2x     10x   5x         2x 2x 4x       2x     2x   5x 5x 2x 2x         5x 3x 2x       3x 3x               84x       4x       2x 2x       2x 2x       2x 2x 2x     2x   2x 2x   4x        
import { Injectable } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeEn from '@angular/common/locales/en';
import { BehaviorSubject, catchError, distinctUntilChanged, EMPTY, filter, firstValueFrom, from, map, Observable, of, switchMap, tap } from 'rxjs';
import { UserService } from './user.service';
import { SessionService } from './session.service';
import { CookieService } from 'ngx-cookie-service'
import { AVAILABLE_LANGS } from '@lang/lang';
 
@Injectable({
  providedIn: 'root'
})
export class LocaleService {
 
  private static UNKNOWN_LANG = 'none';
  private supportedLangs = ['fr', 'en'];
  private defaultLang = 'en';
  private _locale$ = new BehaviorSubject<string>(LocaleService.UNKNOWN_LANG);
  private initialLoadHandled = false;
  private isInitialized = false;
 
  constructor(private sessionService: SessionService, private userService: UserService, private cookieService: CookieService) {}
 
  private save(lang: string): Observable<void> {
    // cookie will allow access to the preferred lang from the front web server (nginx, cloudfront...)
    this.cookieService.delete('lang');
    this.cookieService.set('lang', lang, {expires: 365, path: '/'});
    
    // if user is loggedin, save their lang
    return this.sessionService.isLogged() 
      ? this.userService.saveUserLang(lang).pipe(catchError(() => EMPTY))
      : of(void 0);
  }
 
  private registerLocales() :void {
    registerLocaleData(localeFr, 'fr');
    registerLocaleData(localeEn, 'en');
  }
 
  private handleLangChange(lang: string) :Observable<void> {
    // no change handling before initial load is done
    IIif (!this.initialLoadHandled) return of(void 0);
    // if lang is not available or already is the current lang, no need to do anything
    Eif(!AVAILABLE_LANGS.includes(lang) || this.getCurrentLangFromUrl() === lang) {
      return of(void 0);
    }
    // saves the lang and redirects
    return this.save(lang).pipe(
      tap(() => {
        this.redirectTo(this.buildRedirectUrl(lang));
      })
    );
  }
 
  private observeLocaleChanges(): void {
    // observe locale changes to update user if needed
    this._locale$
      .pipe(
        // don't take unknown lang ie don't handle lang before it is resolved
        filter((l) => l !== LocaleService.UNKNOWN_LANG),
        distinctUntilChanged(), // avoid duplicates
        switchMap((lang) => this.handleLangChange(lang))
      )
      .subscribe();
  }
 
  async init() {
    this.registerLocales();
    this.observeLocaleChanges();
  }
 
  private redirectTo(url: string) :void {
    window.location.assign(url);
  }
 
  private async resolveDefaultLocale() : Promise<string> {
    // get lang from the current user if logged in
    Iif(this.sessionService.isLogged()) {
      let user = await firstValueFrom(this.userService.getUser());
      if(user !== null && user.lang !== null) {
        return user.lang!.toString().toLowerCase();
      }
    }
 
    // get lang from cookie
    const lang = this.cookieService.get('lang');
    Iif(lang !== '') {
      return lang;
    }
 
    // as a fallback, get lang from browser
    const browserLang = navigator.language.split('-')[0]; // e.g.: 'fr-FR' → 'fr'
    return (this.supportedLangs.includes(browserLang) ? browserLang : this.defaultLang).toLowerCase();
  }
 
  get locale$() {
    return this._locale$.asObservable();
  }
 
  get currentLocale(): string {
    return this._locale$.value;
  }
 
  public changeLocale(lang: string) {
    this._locale$.next(lang);
  }
 
  private buildRedirectUrl(lang: string): string {
    const path = location.pathname.replace(/^\/(fr|en)/, '');
    return `/${lang}${path}`;
  }
  
  private getCurrentLangFromUrl(): string {
    const match = window.location.pathname.match(/^\/(fr|en)/);
    return match?.[1] ?? '';
  }
 
  public handle(): Observable<boolean> {
    Eif (!this.isInitialized) {
      this.init();
      this.isInitialized = true;
    }
 
    return from(this.resolveDefaultLocale()).pipe(
      tap((lang) => {
        this.initialLoadHandled = true;
        this.changeLocale(lang);
      }),
      map(() => true)
    );
  }
 
}