All files / proxy/utils/customer-variables customer-variables.ts

100% Statements 18/18
100% Branches 2/2
100% Functions 3/3
100% Lines 18/18

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 6210x 10x                     10x 87x             345x   345x 269x     76x   76x   76x                 345x 622x 622x   621x 269x   269x           1x           76x      
import { CustomerVariableName, CustomerVariableProvider, CustomerVariableType, parseCustomerVariable } from './types'
import { getDefaultCustomerVariable } from './defaults'
 
export interface GetVariableResult<T extends CustomerVariableName> {
  value: CustomerVariableType<T>
  resolvedBy: string | null
}
 
/**
 * Allows access to customer defined variables using multiple providers.
 * Variables will be resolved in order in which providers are set.
 * */
export class CustomerVariables {
  constructor(private readonly providers: CustomerVariableProvider[]) {}
 
  /**
   * Attempts to resolve customer variable using providers.
   * If no provider can resolve the variable, the default value is returned.
   * */
  async getVariable<T extends CustomerVariableName>(variable: T): Promise<GetVariableResult<T>> {
    const providerResult = await this.getValueFromProviders(variable)
 
    if (providerResult) {
      return providerResult
    }
 
    const defaultValue = getDefaultCustomerVariable(variable)
 
    console.debug(`Resolved customer variable ${variable} with default value ${defaultValue}`)
 
    return {
      value: defaultValue,
      resolvedBy: null,
    }
  }
 
  private async getValueFromProviders<T extends CustomerVariableName>(
    variable: T
  ): Promise<GetVariableResult<T> | null> {
    for (const provider of this.providers) {
      try {
        const result = await provider.getVariable(variable)
 
        if (result) {
          console.debug(`Resolved customer variable ${variable} with provider ${provider.name}`)
 
          return {
            value: parseCustomerVariable(variable, result),
            resolvedBy: provider.name,
          }
        }
      } catch (error) {
        console.error(`Error while resolving customer variable ${variable} with provider ${provider.name}`, {
          error,
        })
      }
    }
 
    return null
  }
}