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 | 7x 7x 52x 170x 170x 131x 39x 39x 39x 170x 278x 278x 277x 131x 131x 1x 39x | import { CustomerVariableProvider, CustomerVariableType, CustomerVariableValue } from './types'
import { getDefaultCustomerVariable } from './defaults'
export interface GetVariableResult {
value: CustomerVariableValue
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(variable: CustomerVariableType): Promise<GetVariableResult> {
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(variable: CustomerVariableType): Promise<GetVariableResult | 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: result,
resolvedBy: provider.name,
}
}
} catch (error) {
console.error(`Error while resolving customer variable ${variable} with provider ${provider.name}`, {
error,
})
}
}
return null
}
}
|