All files / src/modules CookiePersistentStore.ts

100% Statements 24/24
100% Branches 7/7
100% Functions 5/5
100% Lines 24/24

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 594x 4x   4x 4x             4x       10x 10x 10x       23x 23x   6x         9x 9x 9x 9x   9x   9x 18x 18x   18x                   9x   9x 4x   5x      
import { PersistentStore } from '@wirewheel/cmp/src/modules/PersistentStore'
import Cookies from 'js-cookie'
 
const ONE_YEAR_IN_DAYS = 365
const COOKIE_KEY = 'wwupcp'
 
type CookiePersistentStoreParams = {
  cookieExpirationInDays?: number
  refreshOnVisit?: boolean
}
 
export class CookiePersistentStore extends PersistentStore {
  private readonly expirationInDays: number
  private readonly refreshOnVisit: boolean
  constructor(params?: CookiePersistentStoreParams) {
    super()
    this.expirationInDays = params?.cookieExpirationInDays || ONE_YEAR_IN_DAYS
    this.refreshOnVisit = params?.refreshOnVisit ?? false
  }
 
  protected read(): any {
    try {
      return JSON.parse(Cookies.get(COOKIE_KEY) as string)
    } catch (cause) {
      return {}
    }
  }
 
  write(value: any): void {
    const hostnameParts = location.hostname.split('.').reverse()
    const parts: string[] = []
    const currentValue = this.read()
    let domain = ''
 
    const expirationDate = this.getExpirationDate(currentValue.expirationDate)
 
    hostnameParts.forEach((val) => {
      parts.push(val)
      domain = [...parts].reverse().join('.')
      // TODO Ensure it only sets the cookie for one domain
      Cookies.set(COOKIE_KEY, JSON.stringify({ ...currentValue, ...value, expirationDate }), {
        domain: domain,
        SameSite: 'None',
        secure: true,
        expires: expirationDate,
      })
    })
  }
 
  private getExpirationDate(currentExpirationDate: Date) {
    const DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000
 
    if (currentExpirationDate && !this.refreshOnVisit) {
      return new Date(currentExpirationDate)
    }
    return new Date(new Date().getTime() + this.expirationInDays * DAY_IN_MILLISECONDS)
  }
}