import Dexie from 'dexie' ; import { Twitter } from 'twit' ; import log from '../log' ; export interface HashtagsScheme { text : string ; timestamp : number ; } export type HashtagsTable = Dexie . Table < HashtagsScheme , string > ; export default class Hashtags { static getScheme ( version ) { switch ( version ) { case 1 : return '&text,timestamp' ; default : log . error ( 'Invalid version number:' , version ) ; return null ; } } constructor ( private table ) { } storeHashtag ( text ) { return this . table . put ( { text , timestamp : Date . now ( ) , } ) . catch ( ( e ) => { log . error ( 'Error on storing hashtag:' , text ) ; throw e ; } ) ; } storeHashtagsInTweet ( json ) { if ( ! json . entities || ! json . entities . hashtags ) { return undefined ; } const hashtags = json . entities . hashtags . map ( h => ( { text : h . text , timestamp : Date . now ( ) , } ) ) ; return this . table . bulkPut ( hashtags ) . catch ( ( e ) => { log . error ( 'Error on storing hashtag in tweet:' , e , hashtags , json ) ; throw e ; } ) ; } storeHashtagsInTweets ( jsons ) { const entries = [ ] as HashtagsScheme [ ] ; const push = Array . prototype . push ; for ( const j of jsons ) { if ( ! j . entities || ! j . entities . hashtags ) { continue ; } const hashtags = j . entities . hashtags . map ( h => ( { text : h . text , timestamp : Date . now ( ) , } ) ) ; push . apply ( entries , hashtags ) ; } if ( entries . length === 0 ) { return undefined ; } return this . table . bulkPut ( entries ) . catch ( ( e ) => { log . error ( 'Error on storing hashtags in tweets:' , e , entries ) ; throw e ; } ) ; } getAllHashtags ( ) { return this . table . toArray ( ) . then ( hs => hs . map ( h => h . text ) ) . catch ( ( e ) : HashtagsScheme [ ] => { log . error ( 'Error on getting all hashtags:' , e ) ; throw e ; } ) ; } getHashtagsStartWith ( str , limit ? ) { const query = limit ? this . table . where ( 'text' ) . startsWith ( str ) . limit ( limit ) : this . table . where ( 'text' ) . startsWith ( str ) ; return query . toArray ( ) . then ( hs => hs . map ( h => h . text ) ) . catch ( ( e ) : string [ ] => { log . error ( `Error on getting accounts which start with ${ str }:` , e ) ; throw e ; } ) ; } getHashtagsExceptFor ( exceptions , limit ? ) { const query = limit ? this . table . where ( 'text' ) . noneOf ( exceptions ) . limit ( limit ) : this . table . where ( 'text' ) . noneOf ( exceptions ) ; return query . toArray ( ) . then ( hs => hs . map ( h => h . text ) ) . catch ( ( e ) : string [ ] => { log . error ( `Error on getting accounts with exceptions:` , exceptions , e ) ; throw e ; } ) ; } dump ( ) { return this . table . toArray ( ) . then ( arr => log . debug ( 'HASHTAGS:' , arr ) ) ; } }