import { Injectable } from '@angular/core'; import { HttpConfig } from '../types'; import { map, take, tap } from 'rxjs/operators'; import { MwHttpConfigService } from './config.service'; import { forkJoin, Observable, of } from 'rxjs'; import { UrlPlaceholderModel } from '../models'; @Injectable() export class MwUrlService { private httpConfig?: HttpConfig; constructor(private httpConfigService: MwHttpConfigService) { this.httpConfigService.getConfig().subscribe((t) => (this.httpConfig = t)); } getBaseUrl(): string | null { return this.httpConfig?.baseUrl || null; } replacePlaceholders(url: string): Observable { if (url.startsWith('/')) { url = this.getBaseUrl() + url; } const placeholders = this.getPlaceholders(url); if (placeholders.length > 0) { const placeholdersArray$ = placeholders.map((t) => t.value.pipe( take(1), map((value) => ({ value, placeholder: t.name, })) ) ); return forkJoin(placeholdersArray$).pipe( map((placeholdersArray) => { placeholdersArray.forEach( (t) => (url = url.replace( new RegExp(`{${t.placeholder}}`, 'g'), t.value )) ); return url; }) ); } return of(url); } private getPlaceholders(url: string): UrlPlaceholderModel[] { const len = this.httpConfig?.urlPlaceholders?.length || 0; if (len > 0) { return ( this.httpConfig?.urlPlaceholders?.filter((t) => new RegExp(`{${t.name}}`, 'g').test(url) ) || [] ); } return []; } }