import moment from 'moment' ; import * as Rx from 'rxjs' ; import { NEWSFEED_DEFAULT_SERVICE_BASE_URL } from '../../common/constants' ; import { ApiItem , FetchResult , NewsfeedPluginBrowserConfig } from '../types' ; import { INewsfeedApiDriver } from './types' ; import { convertItems } from './convert_items' ; import type { NewsfeedStorage } from './storage' ; type ApiConfig = NewsfeedPluginBrowserConfig [ 'service' ] ; interface NewsfeedResponse { items : ApiItem [ ] ; } export class NewsfeedApiDriver implements INewsfeedApiDriver { private readonly kibanaVersion : string ; private readonly loadedTime = moment ( ) . utc ( ) ; constructor ( kibanaVersion , private readonly userLanguage , private readonly fetchInterval , private readonly storage ) { this . kibanaVersion = kibanaVersion . replace ( /^(\d+\.\d+\.\d+).*/ , '$1' ) ; } shouldFetch ( ) { const lastFetchUtc = this . storage . getLastFetchTime ( ) ; if ( ! lastFetchUtc ) { return true ; } const last = moment ( lastFetchUtc ) ; if ( this . loadedTime . diff ( last ) > 0 ) { return true ; } const now = moment . utc ( ) ; const duration = moment . duration ( now . diff ( last ) ) ; return duration . asMilliseconds ( ) > this . fetchInterval ; } fetchNewsfeedItems ( config ) { const urlPath = config . pathTemplate . replace ( '{VERSION}' , this . kibanaVersion ) ; const fullUrl = ( config . urlRoot || NEWSFEED_DEFAULT_SERVICE_BASE_URL ) + urlPath ; const request = new Request ( fullUrl , { method : 'GET' , } ) ; return Rx . from ( window . fetch ( request ) . then ( async ( response ) => { const { items } = ( await response . json ( ) ) as NewsfeedResponse ; return this . convertResponse ( items ) ; } ) ) ; } private convertResponse ( items ) { const feedItems = convertItems ( items , this . userLanguage ) ; const hasNew = this . storage . setFetchedItems ( feedItems . map ( ( item ) => item . hash ) ) ; return { error : null , kibanaVersion : this . kibanaVersion , hasNew , feedItems , } ; } }