@kineticdata/react
Version:
A React library for the Kinetic Platform
203 lines (198 loc) • 8.39 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fetchBridgedResource = exports.countBridgedResource = exports.convertMultipleBridgeRecords = exports.bridgedResourceUrl = exports.bridgedResourceData = exports.arraysToObject = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/objectSpread2"));
var _axios = _interopRequireDefault(require("axios"));
var _qs = _interopRequireDefault(require("qs"));
var _helpers = require("../../helpers");
var _http = require("../http");
/**
* Returns the URL to a bridged resource.
*
* Note: custom sorting is currently not available in this function because the BridgedResource
* API doesn't support it.
*
* @param {*} options - properties to build the bridged resource url
* @param {string} options.bridgedResourceName - name of the bridged resource
* @param {string} options.formSlug - form slug where the bridged resource is defined
* @param {string} options.kappSlug - kapp slug where the bridged resource is defined
* @param {string} options.datastore - flag if the bridged resource is defined on a datastore form
* @returns {string}
*/
var bridgedResourceUrl = exports.bridgedResourceUrl = function bridgedResourceUrl(options) {
var counting = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var _options$kappSlug = options.kappSlug,
kappSlug = _options$kappSlug === void 0 ? _helpers.bundle.kappSlug() : _options$kappSlug,
datastore = options.datastore,
formSlug = options.formSlug,
bridgedResourceName = options.bridgedResourceName;
if (!formSlug) {
throw new Error('Property "formSlug" is required.');
}
if (!bridgedResourceName) {
throw new Error('Property "bridgedResourceName" is required.');
}
var brn = encodeURIComponent(options.bridgedResourceName);
// build the url
var url = !datastore ? "".concat(_helpers.bundle.spaceLocation(), "/").concat(kappSlug, "/").concat(formSlug, "/bridgedResources/").concat(brn) : // Default kapp to 'datastore' if not provided to support deprecated datastore functionality
"".concat(_helpers.bundle.spaceLocation(), "/datastore/").concat(formSlug, "/bridgedResources/").concat(brn);
// append any attributes if they were specified
if (counting) {
url += '/count';
}
return url;
};
/**
* Returns the url encoded data to a bridged resource.
*
* @param {*} options - properties to build the bridged resource url
* @param {string[]=} options.attributes - array of attributes (fields) to return
* @param {number=} options.limit - maximum number of records to retrieve
* @param {number=} options.offset - offset to retrieve as first record
* @param {object=} options.values - hash of value names to values
* @param {object=} options.metadata - hash of metadata names to values
* @returns {string}
*/
var bridgedResourceData = exports.bridgedResourceData = function bridgedResourceData(options) {
var data = {};
// append any attributes if they were specified
if (options.attributes) {
if (!Array.isArray(options.attributes)) {
throw new Error('Property "attributes" expected as array of strings.');
}
if (options.attributes.length > 0) {
data.attributes = options.attributes.join(',');
}
}
// append any parameter values if they were specified
if (options.values && Object.keys(options.values).length > 0) {
data.values = options.values;
}
// append any metadata if it was specified
if (options.metadata && Object.keys(options.metadata).length > 0) {
data.metadata = options.metadata;
}
// append the limit if it was specified
if (options.limit) {
var limit = options.limit;
if (!Number.isInteger(limit)) {
try {
limit = parseInt(limit, 10);
} catch (e) {
throw new Error('Property "limit" expected as a number.');
}
}
data.limit = limit;
}
// append the offset if it was specified
if (options.offset) {
var offset = options.offset;
if (!Number.isInteger(offset)) {
try {
offset = parseInt(offset, 10);
} catch (e) {
throw new Error('Property "offset" expected as a number.');
}
}
data.offset = offset;
}
return _qs["default"].stringify(data);
};
/**
* Combines the field names array with the records array to produce an array of objects
* linking the field name to the field value for each record.
*
* @param {String[]} keys - Array of field names to use as object keys
* @param {Array[]} values - Array of records, which are themselves an array of string values
* @returns {Object[]} Array of objects linking the field name to the field value of each record.
*/
var arraysToObject = exports.arraysToObject = function arraysToObject(keys, values) {
return values.map(function (value) {
return keys.reduce(function (object, key, keyIndex) {
var o = object;
o[key] = value[keyIndex];
return o;
}, {});
});
};
/**
* Converts the results from a Bridged Resource response that contains multiple records.
*
* A bridged resource that is configured to return multiple results separates the field names
* from the record data. This is done to reduce the amount of bandwidth the response uses, but
* it is not the ideal format to work with.
*
* This function combines the field names array with the records array to produce an array of
* objects linking the field name to the field value for each record.
*
* @param {Object} responseJsonRecords - Kinetic Core bridge response parsed from JSON
* @returns {Object[]} Array of objects linking the field name to the field value of each record.
*/
var convertMultipleBridgeRecords = exports.convertMultipleBridgeRecords = function convertMultipleBridgeRecords(responseJsonRecords) {
return arraysToObject(responseJsonRecords.fields, responseJsonRecords.records);
};
var fetchBridgedResource = exports.fetchBridgedResource = function fetchBridgedResource() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var formSlug = options.formSlug,
bridgedResourceName = options.bridgedResourceName;
if (!formSlug) {
throw new Error('Property "formSlug" is required.');
}
if (!bridgedResourceName) {
throw new Error('Property "bridgedResourceName" is required.');
}
return _axios["default"].post(bridgedResourceUrl(options), bridgedResourceData(options), {
headers: (0, _objectSpread2["default"])({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}, (0, _http.headerBuilder)(options))
}).then(function (_ref) {
var data = _ref.data;
var record = data.record,
records = data.records;
if (record) {
return {
record: record.attributes
};
} else if (records) {
return {
records: convertMultipleBridgeRecords(records),
metadata:
// To ensure backwards compatibility continue mapping size to count
records.metadata && typeof records.metadata.size !== 'undefined' ? (0, _objectSpread2["default"])({
count: records.metadata.size
}, records.metadata) : (0, _objectSpread2["default"])({}, records.metadata)
};
}
return {
error: {
statusCode: '500',
message: 'Invalid server response.'
}
};
})["catch"](_http.handleErrors);
};
var countBridgedResource = exports.countBridgedResource = function countBridgedResource() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var formSlug = options.formSlug,
bridgedResourceName = options.bridgedResourceName;
if (!formSlug) {
throw new Error('Property "formSlug" is required.');
}
if (!bridgedResourceName) {
throw new Error('Property "bridgedResourceName" is required.');
}
var counting = true;
return _axios["default"].post(bridgedResourceUrl(options, counting), bridgedResourceData(options), {
headers: (0, _objectSpread2["default"])({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}, (0, _http.headerBuilder)(options))
}).then(function (_ref2) {
var data = _ref2.data;
return {
count: data.count
};
})["catch"](_http.handleErrors);
};