plivo
Version:
A Node.js SDK to make voice calls and send SMS using Plivo and to generate Plivo XML
359 lines (283 loc) • 13.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.InvalidRequestError = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.camelCaseRequestWrapper = camelCaseRequestWrapper;
exports.validateSpeakAttributes = validateSpeakAttributes;
exports.validSubAccount = validSubAccount;
exports.validMultipleDestinationNos = validMultipleDestinationNos;
exports.validMultipleDestinationIntegers = validMultipleDestinationIntegers;
exports.validParam = validParam;
exports.expectedType = expectedType;
exports.expectedValue = expectedValue;
exports.multiValidParam = multiValidParam;
exports.validUrl = validUrl;
exports.isOneAmongStringUrl = isOneAmongStringUrl;
exports.validDateFormat = validDateFormat;
exports.validRange = validRange;
exports.validateStreamAttributes = validateStreamAttributes;
var _camelCase2 = require('lodash/camelCase');
var _camelCase3 = _interopRequireDefault(_camelCase2);
var _snakeCase2 = require('lodash/snakeCase');
var _snakeCase3 = _interopRequireDefault(_snakeCase2);
var _mapKeys2 = require('lodash/mapKeys');
var _mapKeys3 = _interopRequireDefault(_mapKeys2);
var _mapValues2 = require('lodash/mapValues');
var _mapValues3 = _interopRequireDefault(_mapValues2);
var _map2 = require('lodash/map');
var _map3 = _interopRequireDefault(_map2);
var _xml2js = require('xml2js');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var InvalidRequestError = exports.InvalidRequestError = function (_Error) {
_inherits(InvalidRequestError, _Error);
function InvalidRequestError() {
_classCallCheck(this, InvalidRequestError);
return _possibleConstructorReturn(this, (InvalidRequestError.__proto__ || Object.getPrototypeOf(InvalidRequestError)).apply(this, arguments));
}
return InvalidRequestError;
}(Error);
function recursivelyRenameObject(object, renameFunc) {
if (!(object instanceof Object)) {
return object;
}
return (0, _mapValues3.default)((0, _mapKeys3.default)(object, renameFunc), function (value) {
if (Array.isArray(value)) return (0, _map3.default)(value, function (value) {
return recursivelyRenameObject(value, renameFunc);
});
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') return value;
return recursivelyRenameObject(value, renameFunc);
});
}
function camelCaseRequestWrapper(requestFunc) {
return function (method, action, params) {
params = recursivelyRenameObject(params, function (value, key) {
if (typeof key !== 'string') return key;
// Snake Case logic has issue, it replaces double underscores with single
// So dont run snake case logic for following params
var skipParamsFromSnakeCasing = ['message_time__lt', 'message_time__lte', 'message_time__gt', 'message_time__gte', 'end_time__gt', 'end_time__gte', 'end_time__lt', 'end_time__lte', 'bill_duration__gt', 'bill_duration__gte', 'bill_duration__lt', 'bill_duration__lte', 'add_time__gt', 'add_time__gte', 'add_time__lt', 'add_time__lte', 'created__gte', 'created__gt', 'created__lte', 'created__lt', 'renewal_date__gte', 'renewal_date__gt', 'renewal_date__lte', 'renewal_date__lt', 'recording_storage_duration__gt', 'recording_storage_duration__gte', 'recording_storage_duration__lt', 'recording_storage_duration__lte'];
if (skipParamsFromSnakeCasing.indexOf(key) >= 0) {
return key;
}
return (0, _snakeCase3.default)(key).replace('_less_than', '__lt').replace('_greater_than', '__gt').replace('_greater_or_equal', '__gte').replace('_less_or_equal', '__lte').replace('_equal', '').replace('_equals', '').replace('priority_1', 'priority1').replace('priority_2', 'priority2').replace('priority_3', 'priority3').replace('sample_1', 'sample1').replace('sample_2', 'sample2').replace('country_iso_2', 'country_iso2');
});
return requestFunc(method, action, params).then(function (res) {
res.body = recursivelyRenameObject(res.body, function (value, key) {
if (typeof key !== 'string') return key;
return (0, _camelCase3.default)(key);
});
return res;
});
};
}
function validateSpeakAttributes(content, voice) {
if (!voice || ['MAN', 'WOMAN'].indexOf(voice) != -1) {
return { success: true };
}
var voiceParts = voice.split('.');
if (voiceParts.length != 2 || voiceParts[0] != 'Polly') {
return {
success: false, msg: "Invalid voice " + voice + '.'
};
}
;
return {
success: true
};
}
function validSubAccount(accountId) {
if (accountId.constructor !== String) {
throw new InvalidRequestError('Subaccount Id must be a string');
}
if (accountId.length !== 20) {
throw new InvalidRequestError('Subaccount Id should be of length 20');
}
if (accountId.substring(0, 2) !== 'SA') {
throw new InvalidRequestError("Subaccount Id should start with 'SA'");
}
return true;
}
function validMultipleDestinationNos(paramName, paramValue) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (paramValue.split(options.delimiter).length > 1 && options.role.toLowerCase() !== 'agent') {
throw new InvalidRequestError('Multiple ' + paramName + ' values given for role ' + options.role);
} else if (paramValue.split(options.delimiter).length >= options.agentLimit) {
throw new InvalidRequestError('No of ' + paramName + ' values provided should be lesser than ' + options.agentLimit);
} else {
return true;
}
}
function validMultipleDestinationIntegers(paramName, paramValue) {
var val = paramValue.split("<");
for (var i = 0; i < val.length; i++) {
if (!/^-?\d+$/.test(val[i])) {
throw new InvalidRequestError(paramName + " Destination value must be integer");
}
}
return true;
}
function validParam(paramName, paramValue) {
var expectedTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var mandatory = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var expectedValues = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
if (mandatory && !paramValue) {
throw new InvalidRequestError(paramName + " is a required parameter");
}
if (!paramValue) {
return true;
}
if (!expectedValues) {
return expectedType(paramName, expectedTypes, paramValue);
}
if (expectedValue(paramName, expectedValues, paramValue)) {
return true;
}
}
function expectedType(paramName, expectedTypes, paramValue) {
if (!expectedTypes) {
return true;
}
if (expectedTypes.indexOf(paramValue.constructor) === -1) {
throw new InvalidRequestError(paramName + ": Expected one of " + expectedTypes + " but received " + paramValue.constructor + " instead");
}
return true;
}
function expectedValue(paramName, expectedValues, paramValue) {
if (!expectedValues) {
return true;
}
if (expectedValues.constructor === Array) {
if (expectedValues.indexOf(paramValue) === -1) {
throw new InvalidRequestError(paramName + ': Expected one of ' + expectedValues + ' but received ' + paramValue + ' instead');
}
return true;
} else {
if (expectedValues !== paramValue) {
throw new InvalidRequestError(paramName + ': Expected ' + expectedValues + ' but received ' + paramValue + ' instead');
}
return true;
}
}
function multiValidParam(paramName, paramValue) {
var expectedTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var mandatory = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var expectedValues = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
var makeLowerCase = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
var seperator = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : ',';
if (mandatory && !paramValue) {
throw new InvalidRequestError(paramName + 'is a required parameter');
}
if (!paramValue) {
return true;
}
if (makeLowerCase) {
paramValue = paramValue.toLowerCase();
} else {
paramValue = paramValue.toUpperCase();
}
var values = paramValue.split(seperator);
if (expectedValues) {
for (var i = 0; i < values.length; i++) {
expectedValue(paramName, expectedValues, values[i].trim());
}
}
return true;
}
function validUrl(paramName, paramValue) {
var mandatory = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (mandatory && !paramValue) {
throw new InvalidRequestError(paramName + 'is a required parameter');
}
if (!paramValue) {
return true;
}
var response = paramValue.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
if (response == null) {
throw new InvalidRequestError("Invalid URL : Doesn't satisfy the URL format");
} else {
return true;
}
}
function isOneAmongStringUrl(paramName, paramValue) {
var mandatory = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var expectedValues = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
if (mandatory && !paramValue) {
throw new InvalidRequestError(paramName + 'is a required parameter');
}
if (!paramValue) {
return true;
}
if (!(expectedValues.indexOf(paramValue.toLowerCase()) === -1) || !(expectedValues.indexOf(paramValue.toUpperCase()) === -1)) {
return true;
} else if (validUrl(paramName, paramValue)) {
return true;
} else {
throw new InvalidRequestError(paramName + ' neither a valid URL nor in the expected values');
}
}
function validDateFormat(paramName, paramValue) {
var mandatory = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (mandatory && !paramValue) {
throw new InvalidRequestError(paramName + " is a required parameter");
}
if (!paramValue) {
return true;
}
var response = paramValue.match(/^\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}(:\d{2}(\.\d{1,6})?)?$/);
if (response == null) {
throw new InvalidRequestError("Invalid Date : Doesn't satisfy the date format");
} else {
return true;
}
}
function validRange(paramName, paramValue) {
var mandatory = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var lowerBound = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var upperBound = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
if (mandatory && !paramValue) {
throw new InvalidRequestError(paramName + " is a required parameter");
}
if (!paramValue && paramValue !== 0) {
return true;
}
if (!expectedType(paramName, [Number], paramValue)) {
throw new InvalidRequestError(paramName + ": Expected an Integer but received " + paramValue.constructor + " instead");
}
if (lowerBound && upperBound) {
if (paramValue < lowerBound || paramValue > upperBound) {
throw new InvalidRequestError(paramName + " ranges between " + lowerBound + " and " + upperBound);
}
if (paramValue >= lowerBound && paramValue <= upperBound) {
return true;
}
} else if (lowerBound) {
if (paramValue < lowerBound) {
throw new InvalidRequestError(paramName + " should be greater than " + lowerBound);
}
if (paramValue >= lowerBound) {
return true;
}
} else if (upperBound) {
if (paramValue > upperBound) {
throw new InvalidRequestError(paramName + " should be lesser than " + upperBound);
}
if (paramValue <= upperBound) {
return true;
}
} else {
throw new InvalidRequestError("Any one or both of lower and upper bound should be provided");
}
}
function validateStreamAttributes(body, attributes) {
if (!body) {
return { success: false, msg: "No body set for Stream" };
}
return {
success: true,
attributes: attributes
};
}