import { BackendSrvRequest , getBackendSrv } from '@grafana/runtime' ; import cache from 'memory-cache' ; import { Observable } from 'rxjs' ; import { Pair } from 'types' ; export default class Api { cache : any ; baseUrl : string ; params : URLSearchParams ; lastCacheDuration : number | undefined ; constructor ( baseUrl , params ) { this . baseUrl = baseUrl ; this . params = new URLSearchParams ( '?' + params ) ; this . cache = new cache . Cache ( ) ; } /**
     * Queries the API and returns the response data.
     */ async get ( method , path , params ? , headers ? , body ? ) { const paramsData = { } ; ( params ?? [ ] ) . forEach ( ( [ key , value ] ) => { if ( key ) { paramsData [ key ] = value ; } } ) ; this . params . forEach ( ( value , key ) => { paramsData [ key ] = value ; } ) ; const response = this . _request ( method , path , paramsData , headers , body ) ; return ( await response . toPromise ( ) ) . data ; } /**
     * Used as a health check.
     */ async test ( ) { const data = { } ; this . params . forEach ( ( value , key ) => { data [ key ] = value ; } ) ; return this . _request ( 'GET' , '' , data ) . toPromise ( ) ; } /**
     * Returns a cached API response if it exists, otherwise queries the API.
     */ async cachedGet ( cacheDurationSeconds , method , path , params , headers ? , body ? ) { if ( ! cacheDurationSeconds ) { return await this . get ( method , path , params , headers , body ) ; } let cacheKey = this . baseUrl + path ; if ( params && Object . keys ( params ) . length > 0 ) { cacheKey = cacheKey + ( cacheKey . search ( /\?/ ) >= 0 ? '&' : '?' ) + params . map ( ( [ k , v ] ) => `${ encodeURIComponent ( k ) }=${ encodeURIComponent ( v ) }` ) . join ( '&' ) ; } if ( this . lastCacheDuration !== cacheDurationSeconds ) { this . cache . del ( cacheKey ) ; } this . lastCacheDuration = cacheDurationSeconds ; const cachedItem = this . cache . get ( cacheKey ) ; if ( cachedItem ) { return Promise . resolve ( cachedItem ) ; } const result = await this . get ( method , path , params , headers , body ) ; this . cache . put ( cacheKey , result , cacheDurationSeconds * 1000 ) ; return result ; } param path param params _request ( method , path , params ? , headers ? , data ? ) { const recordHeaders = { } ; ( headers ?? [ ] ) . filter ( ( [ key , _ ] ) => key ) . forEach ( ( [ key , value ] ) => { recordHeaders [ key ] = value ; } ) ; const req = { url : this . baseUrl + path , method , headers : recordHeaders , } ; if ( req . method !== 'GET' && data ) { req . data = data ; } req . url = req . url . replace ( /[\/]+/g , '/' ) ; if ( params && Object . keys ( params ) . length > 0 ) { req . url = req . url + ( req . url . search ( /\?/ ) >= 0 ? '&' : '?' ) + Object . entries ( params ) . map ( ( [ k , v ] ) => `${ encodeURIComponent ( k ) }=${ encodeURIComponent ( v ) }` ) . join ( '&' ) ; } return getBackendSrv ( ) . fetch ( req ) ; } }