@kineticdata/react
Version:
A React library for the Kinetic Platform
298 lines (295 loc) • 12.8 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.validateOptions = exports.transformCoreResult = exports.submissionPath = exports.paramBuilder = exports.operations = exports.headerBuilder = exports.handleErrors = exports.generateSortParams = exports.generatePaginationParams = exports.generateCESearchParams = exports.formPath = exports.formDataBuilder = exports.corePath = exports.apiGroup = exports.apiFunction = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/defineProperty"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/toConsumableArray"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/objectSpread2"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/objectWithoutProperties"));
var _axios = _interopRequireDefault(require("axios"));
var _immutable = require("immutable");
var _helpers = require("../helpers");
var _excluded = ["error", "errorKey", "message"];
var types = {
400: 'badRequest',
401: 'unauthorized',
403: 'forbidden',
404: 'notFound',
405: 'methodNotAllowed'
};
var handleErrors = exports.handleErrors = function handleErrors(error) {
// handle a javascript runtime exception by re-throwing it, this is in case we
// make a mistake in a `then` block in one of our api functions.
if (error instanceof Error && !error.response) {
throw error;
}
if (_axios["default"].isCancel(error)) {
return {
error: 'Canceled by user request.'
};
}
// Destructure out the information needed.
var _error$response = error.response,
_error$response$data = _error$response.data,
data = _error$response$data === void 0 ? {} : _error$response$data,
statusCode = _error$response.status,
statusText = _error$response.statusText,
headers = _error$response.headers;
var type = types[statusCode];
var errorMessage = data.error,
_data$errorKey = data.errorKey,
key = _data$errorKey === void 0 ? null : _data$errorKey,
message = data.message,
rest = (0, _objectWithoutProperties2["default"])(data, _excluded);
var result = headers && (!headers['content-type'] || !headers['content-type'].startsWith('application/json')) ? {
message: 'An unexpected error occurred.',
statusCode: statusCode
} : statusCode === 503 ? {
statusCode: statusCode,
message: 'The platform component you are using is not available. Please contact your administrator.'
} : typeof data === 'string' ? {
message: data,
statusCode: statusCode,
key: key
} : (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, rest), {}, {
message: errorMessage || message || statusText,
key: key,
statusCode: statusCode
});
if (type) {
result[type] = true;
}
return {
error: result
};
};
var paramBuilder = exports.paramBuilder = function paramBuilder(options) {
var params = {};
if (options.include) params.include = options.include;
if (options.limit >= 0) params.limit = options.limit;
if (options.pageToken) params.pageToken = options.pageToken;
if (options.q) params.q = options.q;
if (options.direction) params.direction = options.direction;
if (options.orderBy) params.orderBy = options.orderBy;
if (options.manage) params.manage = options.manage;
if (options["export"]) params["export"] = options["export"];
if (options.days) params.days = options.days;
if (options.count) params.count = options.count;
return params;
};
var headerBuilder = exports.headerBuilder = function headerBuilder(options) {
var headers = {};
if (!options["public"]) {
headers['X-Kinetic-AuthAssumed'] = 'true';
}
return headers;
};
var formDataBuilder = exports.formDataBuilder = function formDataBuilder(data, prefix) {
var formData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new FormData();
return Object.keys(data).reduce(function (result, property) {
// Reduce the data object into a FormData object
if (Array.isArray(data[property])) {
// If value of property is an array of non-file objects, recursively add
// each object in the array
if (data[property].some(function (value) {
return typeof value === 'object' && !(value instanceof File);
})) {
data[property].forEach(function (value, index) {
return formDataBuilder(value, prefix ? "".concat(prefix, "[").concat(property, "][").concat(index, "]") : "".concat(property, "[").concat(index, "]"), result);
});
}
// If it's an array of other types, add each value
else {
data[property].forEach(function (value) {
return result.append(prefix ? "".concat(prefix, "[").concat(property, "]") : property, value);
});
}
} else if (typeof data[property] === 'object' && !(data[property] instanceof File)) {
// If value of property is an object that's not a file, append the
// object's nested properties recursively
formDataBuilder(data[property], prefix ? "".concat(prefix, "[").concat(property, "]") : property, result);
} else {
// Otherwise append the value
result.set(prefix ? "".concat(prefix, "[").concat(property, "]") : property, data[property]);
}
return result;
}, formData);
};
/**
*
* @param {string} functionName
* @param {(string|string[])[]} requiredOptions
* The keys of the required options. You can group keys in a nested array if
* only one of a subset is required.
* @param {object} options
* The options object to validate.
*/
var validateOptions = exports.validateOptions = function validateOptions(functionName, requiredOptions, options) {
var missing = requiredOptions.filter(function (requiredOption) {
return Array.isArray(requiredOption) ? !requiredOption.some(function (option) {
return options[option];
}) : !options[requiredOption];
});
if (missing.length > 0) {
throw new Error("".concat(functionName, " failed! The following required options are missing: ").concat(missing.map(function (key) {
return Array.isArray(key) ? key.join(' or ') : key;
}).join(', ')));
}
};
var apiFunction = exports.apiFunction = function apiFunction(_ref) {
var name = _ref.name,
method = _ref.method,
dataOption = _ref.dataOption,
requiredOptions = _ref.requiredOptions,
url = _ref.url,
transform = _ref.transform;
return function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
validateOptions(name, dataOption ? [].concat((0, _toConsumableArray2["default"])(requiredOptions), [dataOption]) : requiredOptions, options);
var urlPostfix = url(options);
return (0, _axios["default"])({
method: method,
url: urlPostfix.startsWith('/app') ? urlPostfix : _helpers.bundle.apiLocation() + urlPostfix,
data: dataOption && options[dataOption],
params: paramBuilder(options),
headers: headerBuilder(options)
}).then(transform)["catch"](handleErrors);
};
};
var apiGroup = exports.apiGroup = function apiGroup(_ref2) {
var _ref3;
var dataOption = _ref2.dataOption,
name = _ref2.name,
plural = _ref2.plural,
singular = _ref2.singular;
return _ref3 = {}, (0, _defineProperty2["default"])(_ref3, "fetch".concat(name, "s"), apiFunction((0, _objectSpread2["default"])({
name: "fetch".concat(name, "s"),
method: 'get'
}, plural))), (0, _defineProperty2["default"])(_ref3, "fetch".concat(name), apiFunction((0, _objectSpread2["default"])({
name: "fetch".concat(name),
method: 'get'
}, singular))), (0, _defineProperty2["default"])(_ref3, "create".concat(name), apiFunction((0, _objectSpread2["default"])((0, _objectSpread2["default"])({
name: "create".concat(name),
dataOption: dataOption,
method: 'post'
}, plural), {}, {
transform: singular.transform
}))), (0, _defineProperty2["default"])(_ref3, "update".concat(name), apiFunction((0, _objectSpread2["default"])({
name: "update".concat(name),
dataOption: dataOption,
method: 'put'
}, singular))), (0, _defineProperty2["default"])(_ref3, "delete".concat(name), apiFunction((0, _objectSpread2["default"])({
name: "delete".concat(name),
method: 'delete'
}, singular))), _ref3;
};
var formPath = exports.formPath = function formPath(_ref4) {
var form = _ref4.form,
kapp = _ref4.kapp;
return !kapp ? form ? "".concat(_helpers.bundle.spaceLocation(), "/app/forms/").concat(form) : "".concat(_helpers.bundle.spaceLocation(), "/app/forms") : form ? "".concat(_helpers.bundle.spaceLocation(), "/").concat(kapp || _helpers.bundle.kappSlug(), "/").concat(form) : "".concat(_helpers.bundle.spaceLocation(), "/").concat(kapp || _helpers.bundle.kappSlug());
};
var submissionPath = exports.submissionPath = function submissionPath(_ref5) {
var submission = _ref5.submission,
datastore = _ref5.datastore;
return datastore ? submission ? "".concat(_helpers.bundle.spaceLocation(), "/app/datastore/submissions/").concat(submission) : "".concat(_helpers.bundle.spaceLocation(), "/app/datastore/submissions") : submission ? "".concat(_helpers.bundle.spaceLocation(), "/submissions/").concat(submission) : "".concat(_helpers.bundle.spaceLocation(), "/submissions");
};
var corePath = exports.corePath = function corePath(_ref6) {
var submission = _ref6.submission,
kapp = _ref6.kapp,
form = _ref6.form,
datastore = _ref6.datastore;
return submission ? submissionPath({
datastore: datastore,
submission: submission
}) : formPath({
form: form,
kapp: kapp
});
};
var operations = exports.operations = (0, _immutable.Map)({
startsWith: function startsWith(field, value) {
return "".concat(field, " =* \"").concat(value, "\"");
},
equals: function equals(field, value) {
return "".concat(field, " = \"").concat(value, "\"");
},
lt: function lt(field, value) {
return "".concat(field, " < \"").concat(value, "\"");
},
lteq: function lteq(field, value) {
return "".concat(field, " <= \"").concat(value, "\"");
},
gt: function gt(field, value) {
return "".concat(field, " > \"").concat(value, "\"");
},
gteq: function gteq(field, value) {
return "".concat(field, " >= \"").concat(value, "\"");
},
"in": function _in(field, value) {
return "".concat(field, " IN (").concat(value.map(function (v) {
return "\"".concat(v, "\"");
}).join(', '), ")");
},
between: function between(field, value) {
return "".concat(field, " BETWEEN (\"").concat(value.get(0), "\", \"").concat(value.get(1), "\")");
}
});
var searchFilters = function searchFilters(filters) {
var q = (0, _immutable.Map)(filters).filter(function (filter) {
return filter.getIn(['value'], '') !== '';
}).map(function (filter, key) {
var mode = filter.getIn(['column', 'filter']);
var op = operations.get(mode, operations.get('startsWith'));
return op(key, filter.get('value'));
}).toIndexedSeq().toList().join(' AND ');
return q.length > 0 ? {
q: q
} : {};
};
var generateSortParams = exports.generateSortParams = function generateSortParams(_ref7) {
var sortColumn = _ref7.sortColumn,
sortDirection = _ref7.sortDirection;
return sortColumn ? {
orderBy: sortColumn,
direction: sortDirection
} : {};
};
var generatePaginationParams = exports.generatePaginationParams = function generatePaginationParams(_ref8) {
var pageSize = _ref8.pageSize,
nextPageToken = _ref8.nextPageToken;
return pageSize && nextPageToken ? {
limit: pageSize,
pageToken: nextPageToken
} : pageSize ? {
limit: pageSize
} : {};
};
var sortParams = function sortParams(sortColumn, sortDirection) {
return sortColumn ? {
orderBy: sortColumn,
direction: sortDirection
} : {};
};
var generateCESearchParams = exports.generateCESearchParams = function generateCESearchParams(_ref9) {
var pageSize = _ref9.pageSize,
filters = _ref9.filters,
sortColumn = _ref9.sortColumn,
sortDirection = _ref9.sortDirection,
nextPageToken = _ref9.nextPageToken;
return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
limit: pageSize,
pageToken: nextPageToken
}, searchFilters(filters)), sortParams(sortColumn, sortDirection));
};
var transformCoreResult = exports.transformCoreResult = function transformCoreResult(envelope) {
return function (result, paramData) {
var count = paramData.nextPageToken ? result.count + paramData.pageTokens.size * paramData.pageSize : result.count;
return {
data: result[envelope],
nextPageToken: result.nextPageToken,
count: count
};
};
};