@trap_stevo/star-vault
Version:
Unleash the future of data management with the ultimate platform for secure, scalable, and dynamic data operations. Power the next generation of applications by combining advanced encryption, revolutionary real-time querying, and seamless synchronization
335 lines (334 loc) • 14.5 kB
JavaScript
"use strict";
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var EngineUtilityManager = require("../HUDManagers/EngineUtilityManager");
var QueryEngine = /*#__PURE__*/function () {
function QueryEngine(storage, security) {
_classCallCheck(this, QueryEngine);
this.security = security;
this.storage = storage;
this.sortCriteria = [];
this.filters = [];
this.data = [];
this.selectedFields = null;
this.limitValue = null;
this.offsetValue = 0;
this.collections = [];
this.callbackFn = null;
}
return _createClass(QueryEngine, [{
key: "from",
value: function from(collections) {
this.collections = Array.isArray(collections) ? collections : [collections];
return this;
}
}, {
key: "where",
value: function where(fieldOrObject, value) {
if (_typeof(fieldOrObject) === "object" && value === undefined) {
this.filters.push(fieldOrObject);
} else if (typeof fieldOrObject === "string") {
if (Array.isArray(value)) {
this.filters.push(_defineProperty({}, fieldOrObject, {
$in: value
}));
} else if (_typeof(value) === "object" && !Array.isArray(value)) {
this.filters.push(_defineProperty({}, fieldOrObject, value));
} else {
this.filters.push(_defineProperty({}, fieldOrObject, {
$eq: value
}));
}
}
return this;
}
}, {
key: "search",
value: function search(field, text) {
var regex = new RegExp(text, "i");
this.filters.push(_defineProperty({}, field, {
$regex: regex
}));
return this;
}
}, {
key: "recent",
value: function recent(field, duration) {
var now = Date.now();
var past = now - EngineUtilityManager.convertDuration(duration);
this.filters.push(_defineProperty({}, field, {
$gte: past
}));
return this;
}
}, {
key: "near",
value: function near(field, center, radius) {
this.filters.push(_defineProperty({}, field, {
$geoWithin: {
center: center,
radius: radius
}
}));
return this;
}
}, {
key: "sort",
value: function sort(criteria) {
this.sortCriteria.push(criteria);
return this;
}
}, {
key: "contains",
value: function contains(value) {
var _this = this;
this.filters.push(function (record) {
return _this.recordContainsValue(record, value);
});
return this;
}
}, {
key: "select",
value: function select(fields) {
this.selectedFields = Array.isArray(fields) ? fields : [fields];
return this;
}
}, {
key: "limit",
value: function limit(value) {
this.limitValue = value;
return this;
}
}, {
key: "offset",
value: function offset(value) {
this.offsetValue = value;
return this;
}
}, {
key: "filterBy",
value: function filterBy(fn) {
this.filters.push(fn);
return this;
}
}, {
key: "callback",
value: function callback(fn) {
this.callbackFn = fn;
return this;
}
}, {
key: "execute",
value: function execute() {
var _this2 = this;
var results = [];
this.collections.forEach(function (collection) {
var _results;
var collectionData = _this2.storage.readAll(collection);
if (!Array.isArray(collectionData)) {
console.warn("Skipped collection \"".concat(collection, "\" \u2014 no data found."));
return null;
}
console.log("Retrieved Records from ".concat(collection, " ~"), collectionData.length);
var decryptedData = collectionData.map(function (record) {
try {
var decryptedRecord = _this2.security.unlock(record.data, collection);
return _objectSpread(_objectSpread({}, record), decryptedRecord || {});
} catch (error) {
console.error("Error decrypting record ~ ".concat(record.id, " in collection ~ \"").concat(collection, "\" ~ ").concat(error.message));
return null;
}
});
(_results = results).push.apply(_results, _toConsumableArray(decryptedData.filter(Boolean)));
});
if (results.length <= 0) {
return results;
}
var _iterator = _createForOfIteratorHelper(this.filters),
_step;
try {
var _loop = function _loop() {
var filter = _step.value;
results = results.filter(function (record) {
if (typeof filter === "function") {
return filter(record.data);
} else if (typeof filter !== "function") {
return _this2.matchesCriteria(record.data, filter);
}
});
};
for (_iterator.s(); !(_step = _iterator.n()).done;) {
_loop();
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
if (this.sortCriteria.length > 0) {
results.sort(function (a, b) {
return _this2.applySorting(a.data, b.data);
});
}
if (this.offsetValue > 0) {
results = results.slice(this.offsetValue);
}
if (this.limitValue !== null) {
results = results.slice(0, this.limitValue);
}
if (this.selectedFields) {
results = results.map(function (record) {
return _this2.projectFields(record.data, _this2.selectedFields);
});
}
if (this.callbackFn) {
results = results.map(function (record) {
return _this2.callbackFn(record);
}).filter(function (record) {
return record !== undefined && record !== null;
});
}
return results;
}
}, {
key: "matchesCriteria",
value: function matchesCriteria(record, criteria) {
for (var key in criteria) {
var condition = criteria[key];
if (_typeof(condition) === "object" && !Array.isArray(condition)) {
if (condition.$gte !== undefined && record[key] < condition.$gte) {
return false;
}
if (condition.$lte !== undefined && record[key] > condition.$lte) {
return false;
}
if (condition.$regex !== undefined && !condition.$regex.test(record[key])) {
return false;
}
if (condition.$geoWithin) {
var _condition$$geoWithin = condition.$geoWithin,
center = _condition$$geoWithin.center,
radius = _condition$$geoWithin.radius;
var distance = this.calculateDistance(record[key], center);
if (distance > radius) {
return false;
}
}
} else if (record[key] !== condition) {
return false;
}
}
return true;
}
}, {
key: "recordContainsValue",
value: function recordContainsValue(obj, target) {
if (_typeof(obj) !== "object" || obj === null) {
return false;
}
for (var key in obj) {
var value = obj[key];
if (_typeof(value) === "object" && value !== null) {
if (this.recordContainsValue(value, target)) {
return true;
}
} else {
if (value === target) {
return true;
}
}
}
return false;
}
}, {
key: "applySorting",
value: function applySorting(a, b) {
var _iterator2 = _createForOfIteratorHelper(this.sortCriteria),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var criterion = _step2.value;
for (var field in criterion) {
var order = criterion[field];
if (a[field] < b[field]) {
return order === "asc" ? -1 : 1;
}
if (a[field] > b[field]) {
return order === "asc" ? 1 : -1;
}
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return 0;
}
}, {
key: "projectFields",
value: function projectFields(record, fields) {
var projected = {};
var _iterator3 = _createForOfIteratorHelper(fields),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var field = _step3.value;
if (record[field] !== undefined) {
projected[field] = record[field];
}
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
return projected;
}
}, {
key: "calculateDistance",
value: function calculateDistance(coord1, coord2) {
var _coord = _slicedToArray(coord1, 2),
lat1 = _coord[0],
lon1 = _coord[1];
var _coord2 = _slicedToArray(coord2, 2),
lat2 = _coord2[0],
lon2 = _coord2[1];
var R = 6371e3;
var φ1 = lat1 * Math.PI / 180;
var φ2 = lat2 * Math.PI / 180;
var Δφ = (lat2 - lat1) * Math.PI / 180;
var Δλ = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
}], [{
key: "range",
value: function range(min, max) {
return {
$gte: min,
$lte: max
};
}
}]);
}();
module.exports = QueryEngine;