All files / src/app/core/utils/state-transfer state-properties.service.ts

100% Statements 28/28
95.23% Branches 20/21
100% Functions 10/10
100% Lines 26/26

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 6599x 99x 99x 99x   99x 99x   99x       5x       8x 4x 2x 3x                 99x 21x           91x       91x 5x 86x 4x   82x         5x 5x 1x 4x     1x     3x            
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable, identity } from 'rxjs';
import { map } from 'rxjs/operators';
 
import { ConfigurationType, getConfigurationState } from 'ish-core/store/core/configuration';
import { mapToProperty } from 'ish-core/utils/operators';
 
import { environment } from '../../../../environments/environment';
import { Environment } from '../../../../environments/environment.model';
 
function isJSON(value: string): boolean {
  return value.trim().startsWith('{');
}
 
function isYAML(value: string) {
  const lines = value.split('\n').filter(x => !!x?.trim());
  return (
    (lines.length > 1 && value.split('\n').some(line => /:\s*$/.test(line))) ||
    lines.every(line => line.includes(': ') || lines.every(line => line.trim().startsWith('- ')))
  );
}
 
/**
 * Service for retrieving injection properties {@link ICM_BASE_URL} and {@link REST_ENDPOINT}.
 * Do not use service directly, inject properties with supplied factory methods instead.
 */
@Injectable({ providedIn: 'root' })
export class StatePropertiesService {
  constructor(private store: Store) {}
 
  /**
   * Retrieve property from first set property of server state, system environment or environment.ts
   */
  getStateOrEnvOrDefault<T>(envKey: string, envPropKey: keyof Environment): Observable<T> {
    return this.store.pipe(
      select(getConfigurationState),
      mapToProperty(envPropKey as keyof ConfigurationType),
      map(value => {
        if (value !== undefined) {
          return value;
        } else if (SSR && process.env[envKey]) {
          return process.env[envKey];
        } else {
          return environment[envPropKey];
        }
      }),
      SSR
        ? map(value => {
            if (typeof value === 'string') {
              if (isJSON(value)) {
                return JSON.parse(value);
              } else if (isYAML(value)) {
                // import js-yaml with require so it doesn't turn up in the client bundle
                // eslint-disable-next-line @typescript-eslint/no-var-requires
                return require('js-yaml').load(value);
              }
            }
            return value;
          })
        : identity
    );
  }
}