@cxco/sdk-webhooks
Version:
DigitalCX Webhook library
140 lines (114 loc) • 3.21 kB
JavaScript
"use strict";
const utils = require('../../utils');
const ValidationResponseModel = require('./ValidationResponseModel');
/**
* Validation Webhook: Inbound payload wrapper class
*/
class ValidationResponse {
constructor(data) {
this.initialRequest = data.inputSlotName === null;
this.hasValidatedValue = false;
this.slotName = data.slot.name;
this.inputSlotName = data.inputSlotName;
this.isCurrentSlot = this.slotName === this.inputSlotName;
this.success = true;
this.error = '';
this.okMessage = data.slot.okMessage;
this.errorMessage = data.slot.errorMessage;
this.missingValueMessage = data.slot.missingValueMessage;
this.originalInputText = data.originalInputText;
this.metadata = data.slot.metadata || {};
this.sessionId = data.sessionId || '';
this.inputPatternMatch = data.inputPatternMatch || '';
this.result = {
quickReplies: data.slot.quickReplies || [],
message: {
text: ''
},
value: data.slot.value,
status: data.slot.status,
resetSlotStatus: [],
metadata: data.slot.metadata || {}
};
}
/**
* Marks the slot status as `"done"`.
* Automatically replaces `%{value}` with the slot value.
*/
done() {
this.hasValidatedValue = true;
this.setMessage(this.okMessage.text.replace('%{value}', this.result.value));
this.result.status = 'done';
}
/**
* Adds error to the response and marks it unsuccessfull.
* Sets `success` to `false`
* @param {string} err
*/
setError(err) {
this.success = false;
this.error = err;
}
/**
* Sets the slot value.
* Side-effect: calls function `done()`.
* @param {string} value
*/
setValue(value) {
this.result.value = utils.removeXss(value);
this.done();
}
/**
* Sets the metadata property
* @param {object} value
*/
setMetadata(value) {
this.result.metadata = value;
}
setMessage(value) {
this.result.message.text = value;
}
getMessage() {
return this.result.message.text;
}
setQuickReplies(quickReplies) {
if (Array.isArray(quickReplies)) {
this.result.quickReplies = quickReplies;
}
}
addQuickReply(quickReply) {
this.result.quickReplies.push(quickReply);
}
setData(data) {
if (Array.isArray(data.quickReplies)) {
this.setQuickReplies(data.quickReplies);
}
if (data.message && typeof data.message.text !== 'undefined') {
this.setMessage(data.message.text);
}
if (typeof data.value !== 'undefined') {
this.setValue(data.value);
}
}
/**
* Sets the slots to be reseted
* @param {string[]} resetSlotStatus
*/
setResetSlotStatus(resetSlotStatus) {
this.result.resetSlotStatus = resetSlotStatus;
}
/**
* creates and returns a ValidationResponseModel object.
*/
toModel() {
if (!this.hasValidatedValue && !this.getMessage() && this.success) {
if (this.isCurrentSlot) {
this.setMessage(this.errorMessage.text);
} else {
this.setMessage(this.missingValueMessage.text);
}
}
return new ValidationResponseModel(this);
}
}
module.exports = ValidationResponse;