import { Observable } from 'rxjs/Observable' ; import { Injectable } from '@angular/core' ; import { Store } from '@ngrx/store' ; import fnsParse from 'date-fns/parse' ; import fnsDiffInMinutes from 'date-fns/difference_in_minutes' ; import { AppState , ITrends , ITrendingHashtag } from '../../reducers' ; import { fetchTrends , fetchedTrends , errorTrends } from '../../actions' ; import { TwitterProvider } from './../twitter/twitter' ; const REFRESH_TRENDS_INTERVAL = 5 ; @ Injectable ( ) export class TrendsProvider { constructor ( public store , private twitterProvider ) { console . log ( 'Hello TrendsProvider Provider' ) ; } isFetching$ ( ) { return this . store . select ( state => state . trends . fetching ) ; } getTrends$ ( ) { return this . store . select ( state => state . trends ) ; } getTrends ( ) { let trends ; this . store . select ( state => state . trends ) . first ( ) . subscribe ( ( trendsState ) => ( trends = trendsState ) ) ; return trends ; } getTrendsHashtags$ ( ) { return this . store . select ( state => state . trends . hashtags ) ; } getTrendsAsOf$ ( ) { return this . store . select ( state => state . trends . as_of ) ; } getTrendsAsOf ( ) { let as_of ; this . getTrendsAsOf$ ( ) . first ( ) . subscribe ( date => ( as_of = date ) ) ; return as_of ; } hasTrendingHashtags ( ) { let hasTrendingHashtags ; this . getTrendsHashtags$ ( ) . first ( ) . subscribe ( ( hashtags ) => ( hasTrendingHashtags = hashtags . length !== 0 ) ) ; return hasTrendingHashtags ; } canFetchNewContent ( ) { const date = fnsParse ( this . getTrendsAsOf ( ) ) ; if ( fnsDiffInMinutes ( Date . now ( ) , date ) < REFRESH_TRENDS_INTERVAL ) { console . info ( `Trends created less than ${ REFRESH_TRENDS_INTERVAL } min ago, keeping existing data` ) ; return false ; } return true ; } fetch$ ( ) { this . store . dispatch ( fetchTrends ( ) ) ; return this . twitterProvider . getTrends$ ( ) . debounceTime ( 500 ) . map ( trends => this . store . dispatch ( fetchedTrends ( trends ) ) ) . catch ( error => { this . store . dispatch ( errorTrends ( ) ) ; return Observable . of ( null ) ; } ) ; } }