All files user.ts

100% Statements 26/26
100% Branches 2/2
100% Functions 6/6
100% Lines 21/21

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 792x 2x                   2x 28x 16x                                           2x 14x 14x   14x   23x             14x 5x 5x     14x 2x             2x     14x 2x 2x     14x               2x  
import { BehaviorSubject } from 'rxjs'
import uuidv4 from 'uuid/v4'
import { PutioAnalyticsCache } from './cache'
 
export interface IPutioAnalyticsUserAttributes {
  anonymousId: string
  id?: string
  hash?: string
  properties?: any
}
 
const createAttributes = (
  cachedAttributes = {},
): IPutioAnalyticsUserAttributes => ({
  anonymousId: uuidv4(),
  id: null,
  hash: null,
  properties: {},
  ...cachedAttributes,
})
 
export interface IPutioAnalyticsUser {
  attributes: BehaviorSubject<IPutioAnalyticsUserAttributes>
  alias: (params: {
    id: string | number
    hash: string
  }) => IPutioAnalyticsUserAttributes
  identify: (params: {
    id: string | number
    hash: string
    properties: any
  }) => IPutioAnalyticsUserAttributes
  clear: () => IPutioAnalyticsUserAttributes
}
 
const createUser = (cache: PutioAnalyticsCache): IPutioAnalyticsUser => {
  const CACHE_KEY = 'pas_js_user'
  const attributes = new BehaviorSubject(createAttributes(cache.get(CACHE_KEY)))
 
  attributes.subscribe({
    next: nextAttributes =>
      cache.set(CACHE_KEY, {
        id: nextAttributes.id,
        anonymousId: nextAttributes.anonymousId,
        hash: nextAttributes.hash,
      }),
  })
 
  const alias = ({ id, hash }) => {
    attributes.next({ ...attributes.getValue(), id: String(id), hash })
    return attributes.getValue()
  }
 
  const identify = ({ id, hash, properties }) => {
    attributes.next({
      ...attributes.getValue(),
      id: String(id),
      hash,
      properties,
    })
 
    return attributes.getValue()
  }
 
  const clear = () => {
    attributes.next(createAttributes())
    return attributes.getValue()
  }
 
  return {
    attributes,
    alias,
    identify,
    clear,
  }
}
 
export default createUser