All files QuotesBloc.ts

100% Statements 109/109
76.47% Branches 13/17
100% Functions 31/31
100% Lines 96/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 2541x             1x 1x 1x 1x             1x 1x     12x                   1x           24x 24x 24x 24x 24x   24x 24x   24x 24x   24x         24x           1x 4x           1x 2x           1x 3x           1x 1x           1x 4x           1x 2x           1x 1x           1x 2x             3x           1x 2x             14x     1x 13x     1x 37x     24x 6x     26x 26x             10x 10x   10x 2x             1x 24x 24x           1x 4x 1x     3x 3x 3x               1x 13x 13x   13x   13x 13x   13x 18x 17x   17x 24x             13x 12x 9x   9x 9x   9x   9x     9x       9x     3x   3x 1x 1x   2x     1x 1x       1x 24x 24x 24x 24x   24x   24x   1x  
import {
  errorCodes,
  HttpResponse,
  QuotesV2,
  QuotesV2Response,
  QuotesV2SearchParams,
} from '@karhoo/demand-api'
import { Subject, Subscription, timer } from 'rxjs'
import { distinctUntilChanged, map, publishReplay, refCount } from 'rxjs/operators'
import { poll } from './polling'
import { QuoteItem, transformer } from './transformer'
 
type QuoteFilters = {
  numOfPassengers: number
  numOfLuggage: number
}
 
const NO_QUOTES_AVAILABLE = errorCodes.K3002
export const defaultValidity = 600
 
function createStream<T>(stream: Subject<T>) {
  return stream.pipe(publishReplay(1), refCount())
}
 
export type QuotesService = Pick<QuotesV2, 'quotesSearch' | 'quotesSearchById'>
 
export type QuotesState = {
  items: QuoteItem[]
  validity: number
}
 
export class QuotesBloc {
  private quotesService: QuotesService
  private _filters: QuoteFilters
  private _searchParams: QuotesV2SearchParams | null
  private _locale?: string
 
  private quotes$ = new Subject<QuotesState>()
  private quotesExpired$ = new Subject()
  private noQuotesFound$ = new Subject()
  private quotesLoadingError$ = new Subject()
  private loading$ = new Subject<boolean>()
 
  private pollingSubscription = new Subscription()
  private timerSubscription = new Subscription()
 
  constructor(quotesService: QuotesService) {
    this.quotesService = quotesService
 
    this._filters = {
      numOfLuggage: 0,
      numOfPassengers: 1,
    }
 
    this._searchParams = null
  }
 
  /**
   * Returns not-filtered quotes stream. Each iteration it is a quotes array
   */
  get quotes() {
    return createStream(this.quotes$)
  }
 
  /**
   * Returns matching quotes stream (by number of passengers and number of luggage filters)
   */
  get matchingQuotes() {
    return this.quotes.pipe(map(({ items }) => items.filter(this.isMatchingQuote)))
  }
 
  /**
   * Returns non-matching quotes stream (by number of passengers and number of luggage filters)
   */
  get otherAvailibleQuotes() {
    return this.quotes.pipe(map(({ items }) => items.filter(q => !this.isMatchingQuote(q))))
  }
 
  /**
   * Emits value once there are no quotes available for given search params
   */
  get noQuotesFound() {
    return createStream(this.noQuotesFound$)
  }
 
  /**
   * Emits true/false when all quotes started/finished to load
   */
  get loading() {
    return createStream(this.loading$).pipe(distinctUntilChanged())
  }
 
  /**
   * Emits a value once loaded quotes are expired
   */
  get quotesExpired() {
    return createStream(this.quotesExpired$)
  }
 
  /**
   * Emits a value with an error if loading of quotes failed
   */
  get quotesLoadingErrors() {
    return createStream(this.quotesLoadingError$)
  }
 
  /**
   * Gets filters value (number of passengers and number of luggage)
   */
  get filters() {
    return this._filters
  }
 
  /**
   * Sets filters value (number of passengers and number of luggage)
   */
  set filters(params: QuoteFilters) {
    this._filters = params
  }
 
  /**
   * Gets quote search params
   */
  get searchParams(): QuotesV2SearchParams | null {
    return this._searchParams
  }
 
  /**
   * Sets quote search params
   */
  set searchParams(params: QuotesV2SearchParams | null) {
    this._searchParams = params
  }
 
  private startLoading() {
    this.loading$.next(true)
  }
 
  private stopLoading() {
    this.loading$.next(false)
  }
 
  private isMatchingQuote = (quote: QuoteItem) =>
    quote.vehiclePassengerCapacity >= this._filters.numOfPassengers &&
    quote.vehicleLuggageCapacity >= this._filters.numOfLuggage
 
  private convertValidityToMS(Ivalidity = 0) {
    return Date.now() + validity * 1000
  }
 
  /**
   * Schedules an `quotes expired` event
   * @param expiresAt {number} Date in miliseconds after which `quotes expired` event is emitted
   */
  scheduleExpiredEvent(IexpiresAt = 0) {
    const expired = timer(expiresAt - Date.now())
 
    this.timerSubscription = expired.subscribe(() => {
      this.quotesExpired$.next()
    })
  }
 
  /**
   * Stops requesting quotes
   */
  stopRequestingQuotes() {
    this.stopLoading()
    this.pollingSubscription.unsubscribe()
  }
 
  /**
   * Requests quotes with previous search params
   */
  refreshQuotes() {
    if (!this._searchParams) {
      throw new Error('searchParams is not defined, try setting it up first')
    }
 
    this.timerSubscription.unsubscribe()
    this.pollingSubscription.unsubscribe()
    this.requestQuotes(this._searchParams, this._locale)
  }
 
  /**
   * Requests quotes with given search params
   * @param params {QuotesSearchParams} search params for quotes
   * @param locale {string} user locale in xx-XX format e.g. en-GB or fr-FR
   */
  async requestQuotes(params: QuotesV2SearchParams, locale?: string) {
    this.searchParams = params
    this._locale = locale
 
    this.startLoading()
 
    this.timerSubscription.unsubscribe()
    this.pollingSubscription.unsubscribe()
 
    const handleQuotesLoaded = (res: HttpResponse<QuotesV2Response>) => {
      if (res.ok) {
        const items = res.body?.quotes || []
 
        this.quotes$.next({
          items: items.map(quote => transformer(quote)),
          validity: this.convertValidityToMS(res.body.validity || defaultValidity),
        })
      }
    }
 
    try {
      const requestQuotesResponse = await this.quotesService.quotesSearch(params)
      if (requestQuotesResponse.ok) {
        const { body } = requestQuotesResponse
 
        handleQuotesLoaded(requestQuotesResponse)
        this.scheduleExpiredEvent(this.convertValidityToMS(body.validity))
 
        const poller = poll(() => this.quotesService.quotesSearchById(body.id, locale))
 
        this.pollingSubscription = poller.subscribe({
          next: handleQuotesLoaded,
          complete: () => {
            this.stopLoading()
          },
        })
 
        return
      }
 
      this.stopLoading()
 
      if (requestQuotesResponse.error.code === NO_QUOTES_AVAILABLE) {
        this.noQuotesFound$.next()
        this.quotesLoadingError$.next(requestQuotesResponse.error)
      } else {
        this.quotesLoadingError$.next(requestQuotesResponse.error)
      }
    } catch (err) {
      this.stopLoading()
      this.quotesLoadingError$.next(err as Error)
    }
  }
 
  dispose() {
    this.quotes$.complete()
    this.noQuotesFound$.complete()
    this.quotesLoadingError$.complete()
    this.loading$.complete()
 
    this.quotesExpired$.complete()
 
    this.stopRequestingQuotes()
  }
}