UNPKG

@cxco/sdk-webhooks

Version:

DigitalCX Webhook library

92 lines (73 loc) 2.24 kB
"use strict"; const ContextResponseModel = require('./ContextResponseModel'); /** * checks whether a value is inside the allowedValues. * @param {string[]} allowedValues * @param {string} value */ function isAllowedValue(allowedValues, value) { return value === null || allowedValues.indexOf(value) >= 0; } /** * Context Webhook: Inbound payload wrapper class */ class ContextResponse { constructor(data) { this.inboundContextVariables = data.contextVariables; this.correlationId = data.correlationId; this.culture = data.culture; this.input = data.input; this.request = data.request; this.session = data.session; this.session.id = data.sessionId; this.user = data.user; this.outboundContextVariables = this.prefillOutCxtVars(data.contextVariables); } prefillOutCxtVars(inCxtVars) { return inCxtVars.map(ctx => ({ key: ctx.key, value: ctx.value })); } /** * Get allowedValues property from the contextVariables * @param {string} key */ getAllowedValues(key) { const cv = this.inboundContextVariables.find(c => c.key === key); if (cv) { return cv.allowedValues; } return undefined; } /** * Adds a context to the `outboundContextVariables` property. * @param {string} contextName * @param {string} contextValue */ setOutboundContextVariable(contextName, contextValue) { const allowedValues = this.getAllowedValues(contextName); if (typeof allowedValues === 'undefined') { throw new Error('Context not found'); } else if (!isAllowedValue(allowedValues, contextValue)) { throw new Error('Context value not allowed'); } const existingContextIndex = this.outboundContextVariables.findIndex(c => c.key === contextName); if (existingContextIndex >= 0) { this.outboundContextVariables[existingContextIndex].value = contextValue; } else { this.outboundContextVariables.push({ key: contextName, value: contextValue }); } } /** * Returns an instance of ContextResponseModel * @returns ContextResponseModel */ toModel() { return new ContextResponseModel(this); } } module.exports = ContextResponse;