All files api.ts

100% Statements 21/21
100% Branches 7/7
100% Functions 6/6
100% Lines 20/20

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 632x 2x 2x                 2x 8x   8x       8x 28x 7x 7x     8x 12x       12x               12x   5x 4x           4x         12x     8x             2x  
import { BehaviorSubject } from 'rxjs'
import { ajax, AjaxError } from 'rxjs/ajax'
import uuid from 'uuid/v4'
import { PutioAnalyticsCache } from './cache'
 
export interface IPutioAnalyticsAPIRetryItem {
  id: string
  path: string
  body: object
}
 
const createAPI = (baseURL: string, cache: PutioAnalyticsCache) => {
  const CACHE_KEY = 'pas_js_retry_queue'
 
  const retryQueue = new BehaviorSubject<IPutioAnalyticsAPIRetryItem[]>(
    (cache.get(CACHE_KEY) || []) as IPutioAnalyticsAPIRetryItem[],
  )
 
  retryQueue.getValue().forEach(retryItem => {
    const next = retryQueue.getValue().filter(i => i.id !== retryItem.id)
    retryQueue.next(next)
    post(retryItem.path, retryItem.body)
  })
 
  retryQueue.subscribe({
    next: v => cache.set(CACHE_KEY, v),
  })
 
  function post(path: string, body: object) {
    const request = ajax({
      url: `${baseURL}${path}`,
      method: 'POST',
      body,
      headers: { 'Content-Type': 'application/json' },
      timeout: 3000,
    })
 
    request.subscribe({
      error: e => {
        if (e instanceof AjaxError && (e.status > 500 || e.status === 0)) {
          const retryItem = {
            id: uuid(),
            path,
            body,
          }
 
          retryQueue.next([...retryQueue.getValue(), retryItem])
        }
      },
    })
 
    return request
  }
 
  return {
    post,
  }
}
 
export type PutioAnalyticsAPI = ReturnType<typeof createAPI>
 
export default createAPI