All files / app/services/db/datasource datasource.service.ts

100% Statements 8/8
100% Branches 4/4
100% Functions 2/2
100% Lines 8/8

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                   201x 201x   201x                         310x 310x 2x     310x                
import { HttpClient, HttpParams } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { Observable, delay } from 'rxjs';
import { ENV } from 'src/environments/injectionToken/environment-provider';
import { IEnvironment } from 'src/environments/interface/ienvironment';
 
/**
 * Data source. Injectable used to provided entity services with proper
 * configuration, such as URI, headers or pipes.
 */
@Injectable({
  providedIn: 'root',
})
export class DatasourceService {
  /** API URL dependant on the environment. */
  public readonly URL: string;
 
  /**
   * Datasource service.
   *
   * @param http The {@link HttpClient}
   */
  constructor(
    @Inject(ENV) private environment: IEnvironment,
    private http: HttpClient
  ) {
    this.URL = this.environment.api;
  }
 
  /**
   * Get request to the api, returning text.
   *
   * @template T The type of the expected json response
   * @param path The request path
   * @param params Additionnal HttpParams
   * @returns An `Observable<T>` of the response, with the response body of type
   *   T
   */
  get<T>(path: string, params: HttpParams = new HttpParams()): Observable<T> {
    let timeout = 0;
    if (!this.environment.production && !this.environment.isTesting)
      timeout =
        Math.random() * this.environment.artificialRandomLoadingTime +
        this.environment.artificialMinLoadingTime;
    return this.http
      .get<T>(`${this.URL}${path}`, {
        responseType: 'json',
        params: params,
      })
      ?.pipe(delay(timeout));
  }
}