import { hashtagRegExp , fromRegExp , mentionRegExp , nearRegExp , sinceRegExp } from './../utils/reg-exp' ; import { Injectable } from '@angular/core' ; import { HttpClient } from '@angular/common/http' ; import { Observable , throwError } from 'rxjs' ; import { catchError , retry } from 'rxjs/operators' ; import { SearchServiceConfig } from '.' ; import { ApiResponse } from '../models/api-response' ; import { defaultUrlConfig } from '../shared/url-config' ; @ Injectable ( ) export class SearchService { constructor ( private http ) { } public fetchQuery ( query , config ) { let jsonpUrl = defaultUrlConfig . loklak . apiServer + '/api/search.json' ; if ( sinceRegExp . exec ( query ) === null && hashtagRegExp . exec ( query ) !== null ) { jsonpUrl += '?callback=JSONP_CALLBACK&timezoneOffset=' + config . getTimezoneOffset ( ) ; } else { jsonpUrl += '?timezoneOffset=' + config . getTimezoneOffset ( ) ; } if ( hashtagRegExp . exec ( query ) !== null ) { jsonpUrl += '&q=%23' + hashtagRegExp . exec ( query ) [ 1 ] + '' + hashtagRegExp . exec ( query ) [ 0 ] ; } else if ( fromRegExp . exec ( query ) !== null ) { jsonpUrl += '&q=from%3A' + fromRegExp . exec ( query ) [ 1 ] ; } else if ( mentionRegExp . exec ( query ) !== null ) { jsonpUrl += '&q=%40' + mentionRegExp . exec ( query ) [ 1 ] ; } else if ( nearRegExp . exec ( query ) !== null ) { jsonpUrl += '&q=near%3A' + nearRegExp . exec ( query ) [ 1 ] ; } else { jsonpUrl += '&q=' + query ; } jsonpUrl += '&minified=' + 'true' + '&source=' + config . source + '&maximumRecords=' + config . maximumRecords . toString ( ) + '&startRecord=' + config . startRecord . toString ( ) ; if ( config . getFilterString ( ) ) { jsonpUrl += '&filter=' + config . getFilterString ( ) ; } return this . http . jsonp < ApiResponse > ( jsonpUrl , 'callback' ) . pipe ( retry ( 2 ) , catchError ( this . handleError ) ) ; } private handleError ( error ) { const errMsg = ( error . message ) ? error . message : error . status ? `${ error . status } - ${ error . statusText }` : 'Server error' ; console . error ( errMsg ) ; return throwError ( errMsg ) ; } }