All files / src/cache shared.ts

100% Statements 15/15
100% Branches 8/8
100% Functions 5/5
100% Lines 13/13

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      2x 2x 2x 41x                     2x           55x 55x 55x               97x       2x 69x     2x 16x                      
import { VisitorData } from '../global'
import { GetOptions } from '@fingerprintjs/fingerprintjs-pro'
 
export const CACHE_KEY_PREFIX = '@fpjs@client@'
export const MAX_CACHE_LIFE = 60 * 60 * 24 // 24 hours
export const DEFAULT_CACHE_LIFE = 60 * 60 // 1 hour
export const DEFAULT_NOW_PROVIDER = () => Date.now()
 
export type CacheEntry<TExtended extends boolean = false> = VisitorData<TExtended>
 
export type Cacheable<TExtended extends boolean = false> = WrappedCacheEntry<TExtended>
 
export type WrappedCacheEntry<TExtended extends boolean = false> = {
  body: CacheEntry<TExtended>
  expiresAt: number
}
 
export class CacheKey<TExtended extends boolean> {
  public tag
  public linkedId
  public extendedResult
 
  constructor(options: GetOptions<TExtended>) {
    this.tag = options.tag || null
    this.linkedId = options.linkedId || null
    this.extendedResult = options.extendedResult ?? false
  }
 
  /**
   * Converts this `CacheKey` instance into a string for use in a cache
   * @returns A string representation of the key
   */
  toKey(): string {
    return `${JSON.stringify(this.tag)}__${JSON.stringify(this.linkedId)}__${this.extendedResult}`
  }
}
 
export function getKeyWithPrefix(key: string, prefix: string) {
  return `${prefix}__${key}`
}
 
export function removePrefixFromKey(key: string, prefix: string) {
  return key.replace(`${prefix}__`, '')
}
 
export type MaybePromise<T> = Promise<T> | T
 
export interface ICache {
  set<T = WrappedCacheEntry>(key: string, entry: T): MaybePromise<void>
  get<T = WrappedCacheEntry>(key: string): MaybePromise<T | undefined>
  remove(key: string): MaybePromise<void>
  allKeys(): MaybePromise<string[]>
}