Warning, /firebird/firebird-ng/src/app/services/server-config.service.ts is written in an unsupported language. File is not indexed.
0001 import { Injectable } from '@angular/core';
0002 import { HttpClient } from '@angular/common/http';
0003 import * as jsoncParser from 'jsonc-parser';
0004 import {deepCopy} from "../utils/deep-copy";
0005 import {BehaviorSubject, Observable, catchError, map, of, firstValueFrom} from "rxjs";
0006
0007
0008 export interface ServerConfig {
0009 servedByPyrobird: boolean;
0010 apiAvailable: boolean;
0011 apiBaseUrl: string;
0012 logLevel: string;
0013 }
0014
0015 export const defaultFirebirdConfig: ServerConfig = {
0016 apiAvailable: false,
0017 apiBaseUrl: "",
0018 servedByPyrobird: false,
0019 logLevel: 'info'
0020 };
0021
0022
0023 @Injectable({
0024 providedIn: 'root'
0025 })
0026 export class ServerConfigService {
0027 private configUrl = 'assets/config.jsonc'; // URL to the JSONC config file
0028 private _config = deepCopy(defaultFirebirdConfig);
0029
0030 private triedLoading = false;
0031
0032 constructor(private http: HttpClient) {}
0033
0034 get config(): ServerConfig {
0035 if (!this.triedLoading) {
0036 this.triedLoading = true;
0037 console.error("[ServerConfigService] config() is called while config is not loaded")
0038 }
0039 return this._config;
0040 }
0041
0042 async loadConfig(): Promise<void> {
0043 try {
0044
0045 const jsoncData = await firstValueFrom(
0046 this.http.get(this.configUrl, { responseType: 'text' })
0047 );
0048 const loadedConfig = this.parseConfig(jsoncData);
0049
0050 // Merge loadedConfig over default config
0051 this._config = { ...defaultFirebirdConfig, ...loadedConfig };
0052 console.log("[ServerConfigService] Server config loaded file")
0053 } catch (error) {
0054 console.error(`Failed to load config: ${error}`);
0055 console.log(`[ServerConfigService] Default config will be used`);
0056 } finally {
0057 this.triedLoading = true;
0058 }
0059 }
0060
0061 private parseConfig(jsoncData: string): Partial<ServerConfig> {
0062 try {
0063 return jsoncParser.parse(jsoncData);
0064 } catch (parseError) {
0065 console.error('Error parsing JSONC data', parseError);
0066 return {};
0067 }
0068 }
0069
0070 /**
0071 * Sets the configuration - intended for use in unit tests only.
0072 * This method is safeguarded to be operational only in non-production environments.
0073 */
0074 public setUnitTestConfig(value: Partial<ServerConfig>) {
0075 this.triedLoading = true;
0076 this._config = {...defaultFirebirdConfig, ...value};
0077 }
0078 }