All files / src/app/services init.service.ts

81.25% Statements 26/32
75% Branches 9/12
100% Functions 6/6
79.31% Lines 23/29

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              118x   59x 59x   59x   59x 59x 59x 59x 59x     59x     59x   59x 59x   59x 59x   59x 59x 59x 59x                 59x 59x 59x 59x                
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { firstValueFrom, Subject } from 'rxjs';
 
@Injectable({
  providedIn: 'root'
})
export class InitService {
 
  apiUrl = "";
  isUrlFound$: Subject<boolean> = new Subject();
 
  constructor(private http: HttpClient) { }
 
  async findApiUrl(){
    const protocol = window.location.protocol;
    const hostname = window.location.hostname.toLowerCase();
    const apiUrls = [];
    Iif (hostname !== "localhost" && hostname.includes('.')){
      apiUrls.push(protocol+"//api."+hostname);
    }
    Iif (hostname !== "frontend-service"){
      apiUrls.push(protocol+"//"+hostname+':5001');
    }
    apiUrls.push(protocol+"//backend-service"); // For ci
 
    const apiUrl: string = "";
    for (const url of apiUrls){
 
      const isUrlValid = await this.checkApiUrl(url);
      Eif (isUrlValid){
        // this.apiUrl$.next(url);
        this.apiUrl = url;
        console.log('found api url', url);
        this.isUrlFound$.next(true);
        return url;
      }
 
    }
    this.isUrlFound$.next(false);
    return apiUrl;
 
  }
 
  async checkApiUrl(url: string): Promise<boolean>{
    try{
      const response = await firstValueFrom(this.http.get<any>(url)); // eslint-disable-line  @typescript-eslint/no-explicit-any
      return typeof response === 'object' && 'twinpad_version' in response;
    }
    catch(e){
      console.error('catched', e);
      return false;}
  }
 
}