diff --git a/app/lib/Aggregate/aggregate_data.js b/app/lib/Aggregate/aggregate_data.js deleted file mode 100644 index 22624672..00000000 --- a/app/lib/Aggregate/aggregate_data.js +++ /dev/null @@ -1,246 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AggregateResult = void 0; -const lodash_1 = require("lodash"); -const validator_1 = require("../Helpers/validator"); -const mongodb_1 = require("mongodb"); -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const item_helpers_1 = require("../Helpers/item_helpers"); -class Aggregate { - constructor(collectionId) { - this._pipeline = new Array(); - this._limitNumber = 50; - this._skipNumber = 0; - this._collectionId = collectionId; - } - filter(filter) { - if (!filter || typeof filter !== "object") { - throw new Error(`WeivData - Filter is empty, please add a filter using weivData.filter method! (filter undefined or not valid)`); - } - else { - const filterClass = (0, validator_1.copyOwnPropsOnly)(filter); - const filters = (0, validator_1.copyOwnPropsOnly)(filterClass._filters); - this._pipeline.push(filters); - return this; - } - } - ascending(...propertyName) { - return this._addSort_(propertyName, 1); - } - descending(...propertyName) { - return this._addSort_(propertyName, -1); - } - group(...propertyName) { - if (!propertyName || !(0, lodash_1.isArray)(propertyName)) { - throw new Error(`WeivData - At least one group property name is required! (propertyName is undefined or not valid)`); - } - else { - const groups = {}; - for (const name of propertyName) { - if (typeof name === "string") { - groups[name] = `$${name}`; - } - else { - throw new Error(`WeivData - Property names must be a string, propertyName value is not valid!`); - } - } - let currentGroupStage = this._pipeline.filter(stage => "$group" in stage)[0]; - if (currentGroupStage) { - currentGroupStage = { - "$group": { - ...currentGroupStage["$group"], - _id: { - ...groups - } - } - }; - } - else { - currentGroupStage = { - "$group": { - _id: { - ...groups - } - } - }; - } - this._pipeline = this._pipeline.filter(stage => !("$group" in stage)); - this._pipeline.push(currentGroupStage); - return this; - } - } - limit(limit) { - if (typeof limit !== "number") { - throw new Error(`WeivData - Unvalid value for limit it's either undefined or not a number!`); - } - else { - this._limitNumber = limit; - return this; - } - } - skip(skip) { - if (typeof skip !== "number") { - throw new Error(`WeivData - Unvalid value for skip it's either undefined or not a number!`); - } - else { - this._skipNumber = skip; - return this; - } - } - avg(propertyName, projectedName) { - return this._addCalculation_(propertyName, `${!projectedName ? propertyName + "Avg" : projectedName}`, "$avg"); - } - count() { - this._pipeline = this._pipeline.map((stage) => { - if (stage["$group"]) { - if (!stage["$group"]["count"]) { - return { - "$group": { - ...stage["$group"], - count: { - "$sum": 1 - } - } - }; - } - } - return stage; - }); - return this; - } - max(propertyName, projectedName) { - return this._addCalculation_(propertyName, `${!projectedName ? propertyName + "Max" : projectedName}`, "$max"); - } - min(propertyName, projectedName) { - return this._addCalculation_(propertyName, `${!projectedName ? propertyName + "Min" : projectedName}`, "$min"); - } - sum(propertyName, projectedName) { - return this._addCalculation_(propertyName, `${!projectedName ? propertyName + "Sum" : projectedName}`, "$sum"); - } - stage(...stages) { - if (!stages || !(0, lodash_1.isArray)(stages)) { - throw new Error(`WeivData - Stage must be a valid stage!`); - } - else { - for (const stage of stages) { - const safeStage = (0, validator_1.copyOwnPropsOnly)(stage); - this._pipeline.push(safeStage); - } - return this; - } - } - _addSort_(propertyName, type) { - if (!propertyName || !(0, lodash_1.isArray)(propertyName)) { - throw new Error(`WeivData - At least one property name is required! (propertyName is undefined or not valid)`); - } - else { - const sort = { - "$sort": {} - }; - for (const name of propertyName) { - if (typeof name === "string") { - sort["$sort"] = { - ...sort["$sort"], - [name]: type - }; - } - else { - throw new Error(`WeivData - Property names must be a string, propertyName value is not valid!`); - } - } - this._pipeline.push(sort); - return this; - } - } - _addCalculation_(propertyName, projectedName, type) { - if (!propertyName || typeof propertyName !== "string" || typeof projectedName !== "string") { - throw new Error(`WeivData - Unvalid value for propertyName projectedName or it's either undefined or not a string!`); - } - else { - let currentGroupStage = this._pipeline.filter(stage => "$group" in stage)[0]; - if (currentGroupStage) { - currentGroupStage = { - "$group": { - _id: null, - ...currentGroupStage["$group"], - [projectedName]: { - [type]: `$${propertyName}` - } - } - }; - } - else { - currentGroupStage = { - "$group": { - _id: null, - [projectedName]: { - [type]: `$${propertyName}` - } - } - }; - } - this._pipeline = this._pipeline.filter((stage) => { - return !stage["$group"]; - }); - this._pipeline.push(currentGroupStage); - return this; - } - } -} -class AggregateResult extends Aggregate { - async run(options) { - try { - const { readConcern, suppressAuth } = options || {}; - await this._handleConnection_(suppressAuth); - const pipeline = [...this._pipeline]; - this._pageSize = this._limitNumber || 50; - const skip = { $skip: this._skipNumber || 0 + ((this._currentPage - 1) * this._pageSize) }; - const limit = { $limit: this._pageSize }; - pipeline.push(skip); - pipeline.push(limit); - const items = await this._collection.aggregate(pipeline, { readConcern }).toArray(); - const length = items.length; - const hasNext = () => this._currentPage * this._pageSize < items.length; - const next = async () => { - try { - this._currentPage++; - return await this.run(options); - } - catch (err) { - throw new Error(`WeivData - Couldn't get the next page of the items!`); - } - }; - return { - items: items.map((item) => { - if (mongodb_1.ObjectId.isValid(item._id)) { - item._id = (0, item_helpers_1.convertObjectId)(item._id); - } - return item; - }), - length, - hasNext, - next, - pipeline - }; - } - catch (err) { - throw new Error(`WeivData - An error occured when running the aggregation pipeline! Pipeline: ${this._pipeline}, Details: ${err}`); - } - } - constructor(collectionId) { - if (!collectionId || typeof collectionId !== "string") { - throw new Error(`WeivData - CollectionID must be string and shouldn't be undefined or null!`); - } - super(collectionId); - this._pageSize = 50; - this._currentPage = 1; - } - async _handleConnection_(suppressAuth) { - if (!this._collection || !this._database) { - const { collection, database } = await (0, connection_helpers_1.connectionHandler)(this._collectionId, suppressAuth); - this._database = database; - this._collection = collection; - } - } -} -exports.AggregateResult = AggregateResult; diff --git a/app/lib/Collections/createCollection.js b/app/lib/Collections/createCollection.js deleted file mode 100644 index 0d3642ac..00000000 --- a/app/lib/Collections/createCollection.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createCollection = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const name_helpers_1 = require("../Helpers/name_helpers"); -const validator_1 = require("../Helpers/validator"); -async function createCollection(collectionId, suppressAuth, createOptions) { - try { - const { safeCollectionOptions } = await (0, validator_1.validateParams)({ collectionId, collectionOptions: createOptions, suppressAuth }, ["collectionId"], "createCollection"); - const { database } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { collectionName } = (0, name_helpers_1.splitCollectionId)(collectionId); - await database.createCollection(collectionName, safeCollectionOptions); - } - catch (err) { - throw new Error(`WeivData - Error when creating a new collection in a database, details: ${err}`); - } -} -exports.createCollection = createCollection; diff --git a/app/lib/Collections/deleteCollection.js b/app/lib/Collections/deleteCollection.js deleted file mode 100644 index cdc42750..00000000 --- a/app/lib/Collections/deleteCollection.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.deleteCollection = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const name_helpers_1 = require("../Helpers/name_helpers"); -const validator_1 = require("../Helpers/validator"); -async function deleteCollection(collectionId, suppressAuth, deleteOptions) { - try { - const { safeCollectionOptions } = await (0, validator_1.validateParams)({ collectionId, collectionOptions: deleteOptions, suppressAuth }, ["collectionId"], "deleteCollection"); - const { database } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { collectionName } = (0, name_helpers_1.splitCollectionId)(collectionId); - return await database.dropCollection(collectionName, safeCollectionOptions); - } - catch (err) { - throw new Error(`WeivData - Error when deleting a collection in a database, details: ${err}`); - } -} -exports.deleteCollection = deleteCollection; diff --git a/app/lib/Collections/listCollections.js b/app/lib/Collections/listCollections.js deleted file mode 100644 index c6d1adc5..00000000 --- a/app/lib/Collections/listCollections.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.listCollections = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const validator_1 = require("../Helpers/validator"); -async function listCollections(databaseName, suppressAuth, filter, listOptions) { - try { - const { safeCollectionFilter, safeCollectionOptions } = await (0, validator_1.validateParams)({ databaseName, suppressAuth, collectionFilter: filter, collectionOptions: listOptions }, ["databaseName"], "listCollections"); - const { database } = await (0, connection_helpers_1.connectionHandler)(`${databaseName}/`, suppressAuth); - return await database.listCollections(safeCollectionFilter, safeCollectionOptions).toArray(); - } - catch (err) { - throw new Error(`WeivData - Error when listing all collections in a database, details: ${err}`); - } -} -exports.listCollections = listCollections; diff --git a/app/lib/Collections/renameCollection.js b/app/lib/Collections/renameCollection.js deleted file mode 100644 index d5b815dc..00000000 --- a/app/lib/Collections/renameCollection.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.renameCollection = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const name_helpers_1 = require("../Helpers/name_helpers"); -const validator_1 = require("../Helpers/validator"); -async function renameCollection(collectionId, newCollectionName, suppressAuth, renameOptions) { - try { - const { safeCollectionOptions } = await (0, validator_1.validateParams)({ collectionId, newCollectionName, suppressAuth, collectionOptions: renameOptions }, ["collectionId", "newCollectionName"], "renameCollection"); - const { database } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { collectionName } = (0, name_helpers_1.splitCollectionId)(collectionId); - await database.renameCollection(collectionName, newCollectionName, safeCollectionOptions); - } - catch (err) { - throw new Error(`WeivData - Error when renaming a collection, details: ${err}`); - } -} -exports.renameCollection = renameCollection; diff --git a/app/lib/Connection/automatic_connection_provider.js b/app/lib/Connection/automatic_connection_provider.js deleted file mode 100644 index 5d8689fc..00000000 --- a/app/lib/Connection/automatic_connection_provider.js +++ /dev/null @@ -1,122 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getClientCache = exports.useClient = void 0; -const mongodb_1 = require("mongodb"); -const permission_helpers_1 = require("./permission_helpers"); -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const node_cache_1 = __importDefault(require("node-cache")); -const clientCache = new node_cache_1.default({ useClones: false, stdTTL: 10 * 60, deleteOnExpire: true }); -const statusCache = new node_cache_1.default({ useClones: false }); -let listeners = false; -let manual = false; -async function setupClient(uri, role) { - try { - const cachedClient = clientCache.get(uri.slice(14, 40)); - if (cachedClient) { - let connection = cachedClient; - if (manual) { - connection = await connectClient(cachedClient, uri); - } - if (connection) { - return connection; - } - else { - throw new Error(`there is a problem with client caching and it's a important problem please report it! This will directly impact to all operations`); - } - } - else { - return createNewClient(uri, role); - } - } - catch (err) { - throw new Error(`Error when connecting to MongoDB Client via setupClient: ${err}`); - } -} -const createNewClient = async (uri, role) => { - try { - const options = await (0, connection_helpers_1.loadConnectionOptions)(role); - if (options.minPoolSize || options.maxPoolSize) { - manual = true; - } - const newMongoClient = new mongodb_1.MongoClient(uri, options); - clientCache.set(uri.slice(14, 40), newMongoClient); - let connection = newMongoClient; - if (manual) { - connection = await connectClient(newMongoClient, uri); - } - if (!listeners) { - clientCache.on('expire', async (_key, client) => { - client.removeAllListeners(); - await client.close(); - console.info("Client Expired and Connection Closed, Listeners Removed"); - }); - clientCache.on('del', async (_key, client) => { - client.removeAllListeners(); - await client.close(); - console.info("Client Deleted and Connection Closed, Listeners Removed"); - }); - listeners = true; - } - if (connection) { - return connection; - } - else { - throw new Error(`Failed to connect to a MongoClient: connection: ${newMongoClient}`); - } - } - catch (err) { - throw new Error(`Error when creating a new MongoDB client: ${err}`); - } -}; -const listenersMap = new Map(); -const connectClient = async (client, uri) => { - try { - const status = statusCache.get(uri.slice(14, 40)); - const cachedClient = clientCache.get(uri.slice(14, 40)); - if (status === true) { - if (cachedClient) { - return cachedClient; - } - } - let connectedClient; - if (!listenersMap.has(uri.slice(14, 40))) { - const handleClose = async () => { - clientCache.del(uri.slice(14, 40)); - statusCache.set(uri.slice(14, 40), false); - }; - const handleError = async () => { - clientCache.del(uri.slice(14, 40)); - statusCache.set(uri.slice(14, 40), false); - throw new Error(`when trying to connect client (connection error): ${uri}`); - }; - client.on('close', handleClose); - client.on('error', handleError); - listenersMap.set(uri.slice(14, 40), true); - } - connectedClient = await client.connect(); - clientCache.set(uri.slice(14, 40), connectedClient); - statusCache.set(uri.slice(14, 40), true); - return connectedClient; - } - catch (err) { - throw new Error(`Unexpected error: ${err}`); - } -}; -async function useClient(suppressAuth = false) { - try { - const { uri, memberId, role } = await (0, permission_helpers_1.getMongoURI)(suppressAuth); - const pool = await setupClient(uri, role); - return { pool, memberId }; - } - catch (err) { - throw new Error(`when connecting to cached MongoClient via useClient: ${err}`); - } -} -exports.useClient = useClient; -function getClientCache() { - return clientCache; -} -exports.getClientCache = getClientCache; diff --git a/app/lib/Connection/permission_helpers.js b/app/lib/Connection/permission_helpers.js deleted file mode 100644 index c53fb8bf..00000000 --- a/app/lib/Connection/permission_helpers.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getPermissionsCache = exports.getMongoURI = void 0; -const wix_users_backend_1 = require("wix-users-backend"); -const secret_helpers_1 = require("../Helpers/secret_helpers"); -const node_cache_1 = __importDefault(require("node-cache")); -const crypto_js_1 = __importDefault(require("crypto-js")); -const encrypt_helpers_1 = require("../Helpers/encrypt_helpers"); -const cache = new node_cache_1.default(); -async function getMongoURI(suppressAuth = false) { - try { - if (suppressAuth != true) { - if (wix_users_backend_1.currentUser.loggedIn === true) { - return getMemberURI(); - } - else { - return getVisitorURI(); - } - } - else { - return getAdminURI(); - } - } - catch (err) { - throw new Error(`Error on getting URI for MongoDB based on permission of current user: ${err}`); - } -} -exports.getMongoURI = getMongoURI; -const getVisitorURI = async () => { - try { - const cachedEncryptedVisitorURI = cache.get("VisitorMongoDB_URI"); - if (cachedEncryptedVisitorURI) { - const cachedVisitorURI = await decryptURI(cachedEncryptedVisitorURI); - return { uri: cachedVisitorURI, role: "visitorClientOptions" }; - } - const secret = await getSecretURI("visitor"); - if (secret) { - const encryptedURI = await encryptURI(secret); - cache.set("VisitorMongoDB_URI", encryptedURI, 60 * 5); - return { uri: secret, role: "visitorClientOptions" }; - } - else { - throw new Error(`WeivDataURIs Secret Not Found or Not Configured Correctly`); - } - } - catch (err) { - throw new Error(`Error when getting VisitorURI: ${err}`); - } -}; -const getAdminURI = async () => { - try { - const cachedEncryptedAdminURI = cache.get("AdminMongoDB_URI"); - if (cachedEncryptedAdminURI) { - const cachedAdminURI = await decryptURI(cachedEncryptedAdminURI); - return { - uri: cachedAdminURI, - memberId: wix_users_backend_1.currentUser.id, - role: "adminClientOptions" - }; - } - const secret = await getSecretURI("admin"); - if (secret) { - const encryptedURI = await encryptURI(secret); - cache.set("AdminMongoDB_URI", encryptedURI, 60 * 5); - return { - uri: secret, - memberId: wix_users_backend_1.currentUser.id, - role: "adminClientOptions" - }; - } - else { - throw new Error(`WeivDataURIs Secret Not Found or Not Configured Correctly`); - } - } - catch (err) { - throw new Error(`Error when getting AdminURI: ${err}`); - } -}; -const getMemberURI = async () => { - try { - const cachedEncryptedMemberURI = cache.get(`MemberMongoDB_URI${wix_users_backend_1.currentUser.id}`); - if (cachedEncryptedMemberURI) { - const cachedMemberURI = await decryptURI(cachedEncryptedMemberURI); - return { - uri: cachedMemberURI, - memberId: wix_users_backend_1.currentUser.id, - role: "memberClientOptions" - }; - } - const cachedRole = cache.get(`MemberRoles${wix_users_backend_1.currentUser.id}`); - if (cachedRole) { - if (cachedRole === "Admin") { - return getAdminURI(); - } - } - const roles = await wix_users_backend_1.currentUser.getRoles(); - if (roles.length > 0) { - cache.set(`MemberRoles${wix_users_backend_1.currentUser.id}`, roles[0].name, 60 * 5); - if (roles[0].name === "Admin") { - return getAdminURI(); - } - } - else { - cache.set(`MemberRoles${wix_users_backend_1.currentUser.id}`, "Member", 60 * 5); - } - const secret = await getSecretURI("member"); - if (secret) { - const encryptedURI = await encryptURI(secret); - cache.set(`MemberMongoDB_URI${wix_users_backend_1.currentUser.id}`, encryptedURI, 60 * 5); - return { - uri: secret, - memberId: wix_users_backend_1.currentUser.id, - role: "memberClientOptions" - }; - } - else { - throw new Error(`WeivDataURIs Secret Not Found or Not Configured Correctly`); - } - } - catch (err) { - throw new Error(`Error when getting MemberURI: ${err}`); - } -}; -function getPermissionsCache() { - return cache; -} -exports.getPermissionsCache = getPermissionsCache; -const encryptURI = async (uri) => { - const secret = await (0, encrypt_helpers_1.getSecretKey)(); - const encrypted = crypto_js_1.default.AES.encrypt(uri, secret, { - mode: crypto_js_1.default.mode.CBC, - paddding: crypto_js_1.default.pad.Pkcs7, - iv: crypto_js_1.default.lib.WordArray.random(16) - }); - return encrypted; -}; -const decryptURI = async (encryptedURI) => { - const secret = await (0, encrypt_helpers_1.getSecretKey)(); - const decrypted = crypto_js_1.default.AES.decrypt(encryptedURI, secret, { - mode: crypto_js_1.default.mode.CBC, - padding: crypto_js_1.default.pad.Pkcs7, - iv: encryptedURI.iv - }); - return decrypted.toString(crypto_js_1.default.enc.Utf8); -}; -const getSecretURI = async (uri) => { - const secret = await (0, secret_helpers_1.getCachedSecret)("WeivDataURIs", true); - return secret[uri]; -}; diff --git a/app/lib/Filter/data_filter.js b/app/lib/Filter/data_filter.js deleted file mode 100644 index 77ed4299..00000000 --- a/app/lib/Filter/data_filter.js +++ /dev/null @@ -1,261 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.WeivDataFilter = void 0; -const lodash_1 = require("lodash"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const validator_1 = require("../Helpers/validator"); -class WeivDataFilter { - constructor() { - this.filters = {}; - } - and(query) { - if (!query) { - throw new Error(`WeivData - query parameter must be valid to work with and method!`); - } - if (!this.filters["$and"]) { - this.filters["$and"] = []; - } - this.filters["$and"].push((0, validator_1.copyOwnPropsOnly)(query.filters)); - return this; - } - between(propertyName, rangeStart, rangeEnd) { - if (!propertyName || typeof propertyName !== "string" || !rangeStart || !rangeEnd) { - throw new Error(`WeivData - propertyName, rangeStart and rangeEnd must have valid values to work with between method!`); - } - if (!this.memoizedBetween) { - this.memoizedBetween = (0, lodash_1.memoize)((propertyName, rangeStart, rangeEnd) => { - return this.addFilter(propertyName, { - $gte: rangeStart, - $lte: rangeEnd, - }); - }); - } - this.memoizedBetween(propertyName, rangeStart, rangeEnd); - return this; - } - contains(propertyName, string) { - if (!propertyName || !string || typeof (propertyName || string) !== "string") { - throw new Error(`WeivData - propertyName and string parameter must be valid to work with contains method!`); - } - if (!this.memoizedContains) { - this.memoizedContains = (0, lodash_1.memoize)((propertyName, string) => { - return this.addFilter(propertyName, { - $regex: string, - $options: "i", - }); - }); - } - this.memoizedContains(propertyName, string); - return this; - } - endsWith(propertyName, string) { - if (!propertyName || !string || typeof (propertyName || string) !== "string") { - throw new Error(`WeivData - propertyName and string parameter must be valid to work with endsWith method!`); - } - if (!this.memoizedEndsWith) { - this.memoizedEndsWith = (0, lodash_1.memoize)((propertyName, string) => { - return this.addFilter(propertyName, { - $regex: `${string}$`, - $options: "i", - }); - }); - } - this.memoizedEndsWith(propertyName, string); - return this; - } - eq(propertyName, value) { - if (!propertyName || !value || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName and value parameter must be valid to work with eq method!`); - } - if (!this.memoizedEq) { - this.memoizedEq = (0, lodash_1.memoize)((propertyName, value) => { - if (propertyName === "_id") { - return this.addFilter(propertyName, { - $eq: (0, item_helpers_1.convertStringId)(value), - }); - } - return this.addFilter(propertyName, { - $eq: value, - }); - }); - } - this.memoizedEq(propertyName, value); - return this; - } - ge(propertyName, value) { - if (!propertyName || !value || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName and value parameter must be valid to work with ge method!`); - } - if (!this.memoizedGe) { - this.memoizedGe = (0, lodash_1.memoize)((propertyName, value) => { - return this.addFilter(propertyName, { $gte: value }); - }); - } - this.memoizedGe(propertyName, value); - return this; - } - gt(propertyName, value) { - if (!propertyName || !value || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName and value parameter must be valid to work with gt method!`); - } - if (!this.memoizedGt) { - this.memoizedGt = (0, lodash_1.memoize)((propertyName, value) => { - return this.addFilter(propertyName, { $gt: value }); - }); - } - this.memoizedGt(propertyName, value); - return this; - } - hasAll(propertyName, value) { - if (!propertyName || !value || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName and value parameter must be valid to work with hasAll method!`); - } - if (!Array.isArray(value)) { - value = [value]; - } - if (!this.memoizedHasAll) { - this.memoizedHasAll = (0, lodash_1.memoize)((propertyName, value) => { - return this.addFilter(propertyName, { $all: value }); - }); - } - this.memoizedHasAll(propertyName, value); - return this; - } - hasSome(propertyName, value) { - if (!propertyName || !value || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName and value parameter must be valid to work with hasSome method!`); - } - if (!Array.isArray(value)) { - value = [value]; - } - if (!this.memoizedHasSome) { - this.memoizedHasSome = (0, lodash_1.memoize)((propertyName, value) => { - return this.addFilter(propertyName, { $in: value }); - }); - } - this.memoizedHasSome(propertyName, value); - return this; - } - isEmpty(propertyName) { - if (!propertyName || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName parameter must be valid to work with isEmpty method!`); - } - if (!this.memoizedIsEmpty) { - this.memoizedIsEmpty = (0, lodash_1.memoize)((propertyName) => { - return this.addFilter(propertyName, { $exists: false }); - }); - } - this.memoizedIsEmpty(propertyName); - return this; - } - isNotEmpty(propertyName) { - if (!propertyName || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName parameter must be valid to work with isNotEmpty method!`); - } - if (!this.memoizedIsNotEmpty) { - this.memoizedIsNotEmpty = (0, lodash_1.memoize)((propertyName) => { - return this.addFilter(propertyName, { $exists: true }); - }); - } - this.memoizedIsNotEmpty(propertyName); - return this; - } - le(propertyName, value) { - if (!propertyName || !value || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName and value parameter must be valid to work with le method!`); - } - if (!this.memoizedLe) { - this.memoizedLe = (0, lodash_1.memoize)((propertyName, value) => { - return this.addFilter(propertyName, { $lte: value }); - }); - } - this.memoizedLe(propertyName, value); - return this; - } - lt(propertyName, value) { - if (!propertyName || !value || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName and value parameter must be valid to work with lt method!`); - } - if (!this.memoizedLt) { - this.memoizedLt = (0, lodash_1.memoize)((propertyName, value) => { - return this.addFilter(propertyName, { $lt: value }); - }); - } - this.memoizedLt(propertyName, value); - return this; - } - ne(propertyName, value) { - if (!propertyName || !value || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName and value parameter must be valid to work with ne method!`); - } - if (!this.memoizedNe) { - this.memoizedNe = (0, lodash_1.memoize)((propertyName, value) => { - return this.addFilter(propertyName, { $ne: value }); - }); - } - this.memoizedNe(propertyName, value); - return this; - } - not(query) { - if (!query) { - throw new Error(`WeivData - query parameter must be valid to work with not method!`); - } - if (!this.filters["$nor"]) { - this.filters["$nor"] = []; - } - this.filters["$nor"].push((0, validator_1.copyOwnPropsOnly)(query.filters)); - return this; - } - or(query) { - if (!query) { - throw new Error(`WeivData - query parameter must be valid to work with or method!`); - } - if (!this.filters["$or"]) { - this.filters["$or"] = []; - } - this.filters["$or"].push((0, validator_1.copyOwnPropsOnly)(query.filters)); - return this; - } - startsWith(propertyName, string) { - if (!propertyName || !string || typeof (propertyName || string) !== "string") { - throw new Error(`WeivData - propertyName and string parameter must be valid to work with startsWith method!`); - } - if (!this.memoizedStartsWith) { - this.memoizedStartsWith = (0, lodash_1.memoize)((propertyName, string) => { - return this.addFilter(propertyName, { - $regex: `^${string}`, - $options: "i", - }); - }); - } - this.memoizedStartsWith(propertyName, string); - return this; - } - addFilter(propertyName, newFilter) { - this.sanitizeFilters(newFilter); - this.filters[propertyName] = { - ...this.filters[propertyName], - ...newFilter - }; - return this.filters; - } - sanitizeFilters(filters) { - for (const key of Object.getOwnPropertyNames(filters)) { - if (key === "__proto__" || key === "constructor" || key === "prototype") { - throw new Error(`Invalid filter key: ${key}`); - } - if (typeof filters[key] === 'object' && filters[key] !== null) { - this.sanitizeFilters(filters[key]); - } - } - } - get _filters() { - const copyFilters = (0, validator_1.copyOwnPropsOnly)(this.filters); - return { - $match: { - ...copyFilters - } - }; - } -} -exports.WeivDataFilter = WeivDataFilter; diff --git a/app/lib/Functions/Helpers/findOne.js b/app/lib/Functions/Helpers/findOne.js deleted file mode 100644 index d7af4f87..00000000 --- a/app/lib/Functions/Helpers/findOne.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.findOne = void 0; -const connection_helpers_1 = require("../../Helpers/connection_helpers"); -const hook_helpers_1 = require("../../Helpers/hook_helpers"); -const hook_manager_1 = require("../../Hooks/hook_manager"); -const node_cache_1 = __importDefault(require("node-cache")); -const validator_1 = require("../../Helpers/validator"); -const item_helpers_1 = require("../../Helpers/item_helpers"); -const cache = new node_cache_1.default({ - checkperiod: 5, - useClones: false, - deleteOnExpire: true -}); -async function findOne(collectionId, propertyName, value, options) { - try { - const { safeValue, safeOptions } = await (0, validator_1.validateParams)({ collectionId, propertyName, value, options }, ["collectionId", "propertyName", "value"], "findOne"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, enableCache, cacheTimeout } = safeOptions || {}; - let editedFilter = { propertyName, value: safeValue }; - if (suppressHooks != true) { - const modifiedFilter = await (0, hook_manager_1.runDataHook)(collectionId, "beforeFindOne", [{ propertyName, value: safeValue }, context]).catch((err) => { - throw new Error(`beforeFindOne Hook Failure ${err}`); - }); - if (modifiedFilter) { - editedFilter = modifiedFilter; - } - } - if (enableCache) { - const cacheKey = `${collectionId}-${editedFilter.propertyName}-${editedFilter.value ? JSON.stringify(editedFilter.value) : "{}"}`; - const cachedItem = cache.get(cacheKey); - if (cachedItem) { - return cachedItem; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const item = await collection.findOne({ [editedFilter.propertyName]: editedFilter.value }, { readConcern }); - if (item) { - if (suppressHooks != true) { - const modifiedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterFindOne", [item, context]).catch((err) => { - throw new Error(`afterFindOne Hook Failure ${err}`); - }); - if (modifiedResult) { - if (modifiedResult._id) { - modifiedResult._id = (0, item_helpers_1.convertObjectId)(modifiedResult._id); - } - if (enableCache) { - cache.set(`${collectionId}-${editedFilter.propertyName}-${editedFilter.value ? JSON.stringify(editedFilter.value) : "{}"}`, modifiedResult, cacheTimeout || 15); - } - return modifiedResult; - } - } - if (item._id) { - const _id = (0, item_helpers_1.convertObjectId)(item._id); - if (enableCache) { - cache.set(`${collectionId}-${editedFilter.propertyName}-${editedFilter.value ? JSON.stringify(editedFilter.value) : "{}"}`, { ...item, _id }, cacheTimeout || 15); - } - return { - ...item, - _id - }; - } - else { - if (enableCache) { - cache.set(`${collectionId}-${editedFilter.propertyName}-${editedFilter.value ? JSON.stringify(editedFilter.value) : "{}"}`, item, cacheTimeout || 15); - } - return item; - } - } - else { - return undefined; - } - } - catch (err) { - throw new Error(`WeivData - Error when finding an item from collection (findOne): ${err}`); - } -} -exports.findOne = findOne; diff --git a/app/lib/Functions/Helpers/getAndRemove.js b/app/lib/Functions/Helpers/getAndRemove.js deleted file mode 100644 index aa118ea7..00000000 --- a/app/lib/Functions/Helpers/getAndRemove.js +++ /dev/null @@ -1,63 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getAndRemove = void 0; -const connection_helpers_1 = require("../../Helpers/connection_helpers"); -const hook_helpers_1 = require("../../Helpers/hook_helpers"); -const hook_manager_1 = require("../../Hooks/hook_manager"); -const item_helpers_1 = require("../../Helpers/item_helpers"); -const validator_1 = require("../../Helpers/validator"); -const member_id_helpers_1 = require("../../Helpers/member_id_helpers"); -async function getAndRemove(collectionId, itemId, options) { - try { - const { safeItemId, safeOptions } = await (0, validator_1.validateParams)({ collectionId, itemId, options }, ["collectionId", "itemId"], "getAndRemove"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, onlyOwner } = safeOptions || {}; - let editedItemId = safeItemId; - if (suppressHooks != true) { - const modifiedItemId = await (0, hook_manager_1.runDataHook)(collectionId, "beforeGetAndRemove", [safeItemId, context]).catch((err) => { - throw new Error(`beforeGetAndRemove Hook Failure ${err}`); - }); - if (modifiedItemId) { - editedItemId = (0, item_helpers_1.convertStringId)(modifiedItemId); - } - } - const filter = { _id: editedItemId }; - if (onlyOwner) { - const currentMemberId = await (0, member_id_helpers_1.getOwnerId)(); - if (currentMemberId) { - filter._owner = currentMemberId; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const item = await collection.findOneAndDelete(filter, { readConcern, includeResultMetadata: false }); - if (item) { - if (suppressHooks != true) { - const modifiedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterGetAndRemove", [item, context]).catch((err) => { - throw new Error(`afterGetAndRemove Hook Failure ${err}`); - }); - if (modifiedResult) { - if (modifiedResult._id) { - modifiedResult._id = (0, item_helpers_1.convertObjectId)(modifiedResult._id); - } - return modifiedResult; - } - } - if (item._id) { - return { - ...item, - _id: (0, item_helpers_1.convertObjectId)(item._id) - }; - } - else { - return item; - } - } - else { - return undefined; - } - } - catch (err) { - throw new Error(`WeivData - Error when removing an item from collection (getAndRemove): ${err}`); - } -} -exports.getAndRemove = getAndRemove; diff --git a/app/lib/Functions/Helpers/getAndReplace.js b/app/lib/Functions/Helpers/getAndReplace.js deleted file mode 100644 index ca43bdb1..00000000 --- a/app/lib/Functions/Helpers/getAndReplace.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getAndReplace = void 0; -const connection_helpers_1 = require("../../Helpers/connection_helpers"); -const hook_helpers_1 = require("../../Helpers/hook_helpers"); -const hook_manager_1 = require("../../Hooks/hook_manager"); -const validator_1 = require("../../Helpers/validator"); -const member_id_helpers_1 = require("../../Helpers/member_id_helpers"); -const item_helpers_1 = require("../../Helpers/item_helpers"); -async function getAndReplace(collectionId, itemId, value, options) { - try { - const { safeItemId, safeValue, safeOptions } = await (0, validator_1.validateParams)({ collectionId, itemId, value, options }, ["collectionId", "itemId", "value"], "getAndReplace"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, onlyOwner } = safeOptions || {}; - let editedItem = safeValue; - if (suppressHooks != true) { - const modifiedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeGetAndReplace", [safeValue, context]).catch((err) => { - throw new Error(`beforeGetAndReplace Hook Failure ${err}`); - }); - if (modifiedItem) { - editedItem = modifiedItem; - } - } - delete editedItem._id; - const filter = { _id: safeItemId }; - if (onlyOwner) { - const currentMemberId = await (0, member_id_helpers_1.getOwnerId)(); - if (currentMemberId) { - filter._owner = currentMemberId; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const item = await collection.findOneAndReplace(filter, editedItem, { readConcern, returnDocument: "after", includeResultMetadata: false }); - if (item) { - if (suppressHooks != true) { - const modifiedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterGetAndReplace", [item, context]).catch((err) => { - throw new Error(`afterGetAndReplace Hook Failure ${err}`); - }); - if (modifiedResult) { - if (modifiedResult._id) { - modifiedResult._id = (0, item_helpers_1.convertObjectId)(modifiedResult._id); - } - return modifiedResult; - } - } - if (item._id) { - return { - ...item, - _id: (0, item_helpers_1.convertObjectId)(item._id) - }; - } - else { - return item; - } - } - else { - return undefined; - } - } - catch (err) { - throw new Error(`WeivData - Error when replacing an item from collection (getAndReplace): ${err}`); - } -} -exports.getAndReplace = getAndReplace; diff --git a/app/lib/Functions/Helpers/getAndUpdate.js b/app/lib/Functions/Helpers/getAndUpdate.js deleted file mode 100644 index dbd0a620..00000000 --- a/app/lib/Functions/Helpers/getAndUpdate.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getAndUpdate = void 0; -const connection_helpers_1 = require("../../Helpers/connection_helpers"); -const hook_helpers_1 = require("../../Helpers/hook_helpers"); -const hook_manager_1 = require("../../Hooks/hook_manager"); -const validator_1 = require("../../Helpers/validator"); -const member_id_helpers_1 = require("../../Helpers/member_id_helpers"); -const item_helpers_1 = require("../../Helpers/item_helpers"); -async function getAndUpdate(collectionId, itemId, value, options) { - try { - const { safeItemId, safeValue, safeOptions } = await (0, validator_1.validateParams)({ collectionId, itemId, value, options }, ["collectionId", "itemId", "value"], "getAndUpdate"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, onlyOwner } = safeOptions || {}; - let editedItem = safeValue; - if (suppressHooks != true) { - const modifiedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeGetAndUpdate", [safeValue, context]).catch((err) => { - throw new Error(`beforeGetAndUpdate Hook Failure ${err}`); - }); - if (modifiedItem) { - editedItem = modifiedItem; - } - } - delete editedItem._id; - const filter = { _id: safeItemId }; - if (onlyOwner) { - const currentMemberId = await (0, member_id_helpers_1.getOwnerId)(); - if (currentMemberId) { - filter._owner = currentMemberId; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const item = await collection.findOneAndUpdate(filter, { $set: editedItem }, { readConcern, returnDocument: "after", includeResultMetadata: false }); - if (item) { - if (suppressHooks != true) { - const modifiedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterGetAndUpdate", [item, context]).catch((err) => { - throw new Error(`afterGetAndUpdate Hook Failure ${err}`); - }); - if (modifiedResult) { - if (modifiedResult._id) { - modifiedResult._id = (0, item_helpers_1.convertObjectId)(modifiedResult._id); - } - return modifiedResult; - } - } - if (item._id) { - return { - ...item, - _id: (0, item_helpers_1.convertObjectId)(item._id) - }; - } - else { - return item; - } - } - else { - return undefined; - } - } - catch (err) { - throw new Error(`WeivData - Error when updating an item from collection (getAndUpdate): ${err}`); - } -} -exports.getAndUpdate = getAndUpdate; diff --git a/app/lib/Functions/QueryReferenced/queryReferenced.js b/app/lib/Functions/QueryReferenced/queryReferenced.js deleted file mode 100644 index e4d8bc92..00000000 --- a/app/lib/Functions/QueryReferenced/queryReferenced.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.queryReferenced = void 0; -const query_referenced_result_1 = require("./query_referenced_result"); -const validator_1 = require("../../Helpers/validator"); -async function queryReferenced(collectionId, targetCollectionId, itemId, propertyName, queryOptions, options) { - try { - const { safeItemId, safeQueryOptions, safeOptions } = await (0, validator_1.validateParams)({ collectionId, targetCollectionId, itemId, propertyName, queryOptions, options }, ["collectionId", "targetCollectionId", "itemId", "propertyName"], "queryReferenced"); - const referencedClass = new query_referenced_result_1.QueryReferencedResult(collectionId, targetCollectionId, safeItemId, propertyName, safeQueryOptions || { pageSize: 50, order: 'asc' }, safeOptions || {}); - return await referencedClass.getResult(); - } - catch (err) { - throw new Error(`WeivData - Error when querying referenced items: ${err}`); - } -} -exports.queryReferenced = queryReferenced; diff --git a/app/lib/Functions/QueryReferenced/query_referenced_result.js b/app/lib/Functions/QueryReferenced/query_referenced_result.js deleted file mode 100644 index fc627683..00000000 --- a/app/lib/Functions/QueryReferenced/query_referenced_result.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.QueryReferencedResult = void 0; -const query_referenced_helpers_1 = require("../../Helpers/query_referenced_helpers"); -const connection_helpers_1 = require("../../Helpers/connection_helpers"); -const item_helpers_1 = require("../../Helpers/item_helpers"); -class QueryReferencedResult { - constructor(collectionId, targetCollectionId, itemId, propertyName, queryOptions, options) { - this.currentPage = 0; - this.pageSize = 50; - if (!collectionId || !targetCollectionId || !itemId || !propertyName || !queryOptions || !options) { - throw new Error(`one or more required param is undefined - Required Params: collectionId, targetCollectionId, propertyName, queryOptions, options, itemId`); - } - this._collectionId = collectionId; - this.targetCollectionId = targetCollectionId; - this.itemId = itemId; - this.propertyName = propertyName; - this.options = options; - this.pageSize = queryOptions.pageSize || 50; - this.order = queryOptions.order || 'asc'; - } - async getResult() { - try { - const { suppressAuth, readConcern } = this.options; - await this._handleConnection_(suppressAuth); - const pipelineOptions = this.__getPipelineOptions__(); - const pipeline = (0, query_referenced_helpers_1.getPipeline)(this.itemId, this.targetCollectionId, this.propertyName, pipelineOptions); - const aggregate = this._collection.aggregate(pipeline, { readConcern }); - const items = await aggregate.toArray(); - const hasNext = await aggregate.hasNext(); - const { referencedItems, totalItems } = items[0]; - return { - items: referencedItems.map((item) => { - if (item._id) { - item._id = (0, item_helpers_1.convertObjectId)(item._id); - } - return item; - }), - totalCount: totalItems, - hasNext: () => hasNext, - hasPrev: () => this.currentPage > 0, - next: async () => { - this.currentPage++; - return await this.getResult(); - }, - prev: async () => { - this.currentPage--; - return await this.getResult(); - } - }; - } - catch (err) { - throw new Error(`when running queryReferenced function: ${err}`); - } - } - async _handleConnection_(suppressAuth) { - if (!this._collection || !this._database) { - const { collection, database } = await (0, connection_helpers_1.connectionHandler)(this._collectionId, suppressAuth); - this._database = database; - this._collection = collection; - } - } - __getPipelineOptions__() { - return { - pageSize: this.pageSize, - skip: this.pageSize * this.currentPage, - order: this.order - }; - } -} -exports.QueryReferencedResult = QueryReferencedResult; diff --git a/app/lib/Functions/bulkInsert.js b/app/lib/Functions/bulkInsert.js deleted file mode 100644 index 60a18104..00000000 --- a/app/lib/Functions/bulkInsert.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.bulkInsert = void 0; -const member_id_helpers_1 = require("../Helpers/member_id_helpers"); -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const validator_1 = require("../Helpers/validator"); -const item_helpers_1 = require("../Helpers/item_helpers"); -async function bulkInsert(collectionId, items, options) { - try { - const { safeItems, safeOptions } = await (0, validator_1.validateParams)({ collectionId, items, options }, ["collectionId", "items"], "bulkInsert"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, enableVisitorId, readConcern } = safeOptions || {}; - let ownerId = await (0, member_id_helpers_1.getOwnerId)(enableVisitorId); - let editedItems = safeItems.map(async (item) => { - item._updatedDate = new Date(); - item._createdDate = new Date(); - item._owner = ownerId; - if (suppressHooks != true) { - let editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeInsert", [item, context]).catch((err) => { - throw new Error(`beforeInsert (bulkInsert) Hook Failure ${err}`); - }); - if (editedItem) { - item = editedItem; - } - } - return item; - }); - editedItems = await Promise.all(editedItems); - const writeOperations = editedItems.map((value) => { - return { - insertOne: { - document: value - } - }; - }); - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { insertedIds, insertedCount, ok } = await collection.bulkWrite(writeOperations, { readConcern, ordered: true }); - const insertedItemIds = Object.keys(insertedIds).map((key) => { - return (0, item_helpers_1.convertObjectId)(insertedIds[key]); - }); - if (ok) { - if (suppressHooks != true) { - editedItems = editedItems.map(async (item) => { - if (item._id) { - item._id = (0, item_helpers_1.convertObjectId)(item._id); - } - const editedInsertItem = await (0, hook_manager_1.runDataHook)(collectionId, "afterInsert", [item, context]).catch((err) => { - throw new Error(`afterInsert (bulkInsert) Hook Failure ${err}`); - }); - if (editedInsertItem) { - return editedInsertItem; - } - else { - return item; - } - }); - editedItems = await Promise.all(editedItems); - } - return { insertedItems: editedItems, insertedItemIds, inserted: insertedCount }; - } - else { - throw new Error(`inserted: ${insertedCount}, ok: ${ok}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when inserting items using bulkInsert: ${err}`); - } -} -exports.bulkInsert = bulkInsert; diff --git a/app/lib/Functions/bulkRemove.js b/app/lib/Functions/bulkRemove.js deleted file mode 100644 index c4afa307..00000000 --- a/app/lib/Functions/bulkRemove.js +++ /dev/null @@ -1,59 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.bulkRemove = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const validator_1 = require("../Helpers/validator"); -const member_id_helpers_1 = require("../Helpers/member_id_helpers"); -async function bulkRemove(collectionId, itemIds, options) { - try { - const { safeItemIds, safeOptions } = await (0, validator_1.validateParams)({ collectionId, itemIds, options }, ["collectionId", "itemIds"], "bulkRemove"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, onlyOwner } = safeOptions || {}; - let currentMemberId; - if (onlyOwner) { - currentMemberId = await (0, member_id_helpers_1.getOwnerId)(); - } - let editedItemIds = safeItemIds.map(async (itemId) => { - if (suppressHooks != true) { - const editedId = await (0, hook_manager_1.runDataHook)(collectionId, "beforeRemove", [itemId, context]).catch((err) => { - throw new Error(`beforeRemove (bulkRemove) Hook Failure ${err}`); - }); - if (editedId) { - return (0, item_helpers_1.convertStringId)(editedId); - } - else { - return (0, item_helpers_1.convertStringId)(itemId); - } - } - else { - return (0, item_helpers_1.convertStringId)(itemId); - } - }); - editedItemIds = await Promise.all(editedItemIds); - const writeOperations = editedItemIds.map((itemId) => { - const filter = { _id: itemId }; - if (onlyOwner && currentMemberId) { - filter._owner = currentMemberId; - } - return { deleteOne: { filter } }; - }); - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { deletedCount, ok } = await collection.bulkWrite(writeOperations, { readConcern, ordered: true }); - if (ok) { - return { - removed: deletedCount, - removedItemIds: editedItemIds.map(id => (0, item_helpers_1.convertObjectId)(id)) - }; - } - else { - throw new Error(`removed: ${deletedCount}, ok: ${ok}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when removing items using bulkRemove: ${err}`); - } -} -exports.bulkRemove = bulkRemove; diff --git a/app/lib/Functions/bulkSave.js b/app/lib/Functions/bulkSave.js deleted file mode 100644 index 593ee2cc..00000000 --- a/app/lib/Functions/bulkSave.js +++ /dev/null @@ -1,132 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.bulkSave = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const member_id_helpers_1 = require("../Helpers/member_id_helpers"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const validator_1 = require("../Helpers/validator"); -async function bulkSave(collectionId, items, options) { - try { - const { safeItems, safeOptions } = await (0, validator_1.validateParams)({ collectionId, items, options }, ["collectionId", "items"], "bulkSave"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, enableVisitorId, readConcern, onlyOwner } = safeOptions || {}; - const currentMemberId = await (0, member_id_helpers_1.getOwnerId)(enableVisitorId); - let ownerId = await (0, member_id_helpers_1.getOwnerId)(enableVisitorId); - let editedItems = safeItems.map(async (item) => { - if (!item._owner) { - item._owner = ownerId; - } - if (item._id) { - if (suppressHooks != true) { - const editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeUpdate", [item, context]).catch((err) => { - throw new Error(`beforeUpdate (bulkSave) Hook Failure ${err}`); - }); - if (editedItem) { - editedItem._id = (0, item_helpers_1.convertStringId)(editedItem._id); - return editedItem; - } - else { - item._id = (0, item_helpers_1.convertStringId)(item._id); - return item; - } - } - else { - item._id = (0, item_helpers_1.convertStringId)(item._id); - return item; - } - } - else { - item._owner = currentMemberId; - if (suppressHooks != true) { - const editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeInsert", [item, context]).catch((err) => { - throw new Error(`beforeInsert (bulkSave) Hook Failure ${err}`); - }); - if (editedItem) { - return editedItem; - } - else { - return item; - } - } - else { - return item; - } - } - }); - editedItems = await Promise.all(editedItems); - const bulkOperations = editedItems.map((item) => { - if (item._id) { - const filter = { _id: item._id }; - if (onlyOwner) { - if (currentMemberId) { - filter._owner = currentMemberId; - } - } - return { - updateOne: { - filter, - update: { $set: { ...item, _updatedDate: new Date() }, $setOnInsert: !item._createdDate ? { _createdDate: new Date() } : {} }, - upsert: true - } - }; - } - else { - return { - insertOne: { - document: item - } - }; - } - }); - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { insertedCount, modifiedCount, insertedIds, ok } = await collection.bulkWrite(bulkOperations, { readConcern }); - if (ok) { - if (suppressHooks != true) { - editedItems = editedItems.map(async (item) => { - if (item._id) { - item._id = (0, item_helpers_1.convertObjectId)(item._id); - const editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "afterUpdate", [item, context]).catch((err) => { - throw new Error(`afterUpdate (bulkSave) Hook Failure ${err}`); - }); - if (editedItem) { - return editedItem; - } - else { - return item; - } - } - else { - const editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "afterInsert", [item, context]).catch((err) => { - throw new Error(`afterInsert Hook Failure ${err}`); - }); - if (editedItem) { - return editedItem; - } - else { - return item; - } - } - }); - editedItems = await Promise.all(editedItems); - } - const editedInsertedIds = Object.keys(insertedIds).map((key) => { - return (0, item_helpers_1.convertObjectId)(insertedIds[key]); - }); - return { - insertedItemIds: editedInsertedIds, - inserted: insertedCount, - updated: modifiedCount, - savedItems: editedItems - }; - } - else { - throw new Error(`inserted: ${insertedCount}, updated: ${modifiedCount}, ok: ${ok}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when saving items using bulkSave: ${err}`); - } -} -exports.bulkSave = bulkSave; diff --git a/app/lib/Functions/bulkUpdate.js b/app/lib/Functions/bulkUpdate.js deleted file mode 100644 index 0a3498aa..00000000 --- a/app/lib/Functions/bulkUpdate.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.bulkUpdate = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const validator_1 = require("../Helpers/validator"); -const member_id_helpers_1 = require("../Helpers/member_id_helpers"); -async function bulkUpdate(collectionId, items, options) { - try { - const { safeItems, safeOptions } = await (0, validator_1.validateParams)({ collectionId, items, options }, ["collectionId", "items"], "bulkUpdate"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, onlyOwner } = safeOptions || {}; - const currentMemberId = await (0, member_id_helpers_1.getOwnerId)(); - let editedItems = safeItems.map(async (item) => { - item._id = (0, item_helpers_1.convertStringId)(item._id); - if (suppressHooks != true) { - const editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeUpdate", [item, context]).catch((err) => { - throw new Error(`beforeUpdate (bulkUpdate) Hook Failure ${err}`); - }); - if (editedItem) { - return editedItem; - } - else { - return item; - } - } - else { - return item; - } - }); - editedItems = await Promise.all(editedItems); - const bulkOperations = editedItems.map((item) => { - const filter = { _id: item._id }; - if (onlyOwner) { - if (currentMemberId) { - filter._owner = currentMemberId; - } - } - return { - updateOne: { - filter, - update: { $set: { ...item, _updatedDate: new Date() } } - } - }; - }); - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { modifiedCount, ok } = await collection.bulkWrite(bulkOperations, { readConcern, ordered: true }); - if (ok) { - if (suppressHooks != true) { - editedItems = editedItems.map(async (item) => { - if (item._id) { - item._id = (0, item_helpers_1.convertObjectId)(item._id); - } - const editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "afterUpdate", [item, context]).catch((err) => { - throw new Error(`afterUpdate (bulkUpdate) Hook Failure ${err}`); - }); - if (editedItem) { - return editedItem; - } - else { - return item; - } - }); - editedItems = await Promise.all(editedItems); - } - return { - updated: modifiedCount, - updatedItems: editedItems - }; - } - else { - throw new Error(`updated: ${modifiedCount}, ok: ${ok}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when updating items using bulkUpdate: ${err}`); - } -} -exports.bulkUpdate = bulkUpdate; diff --git a/app/lib/Functions/convertId.js b/app/lib/Functions/convertId.js deleted file mode 100644 index 9c3b34d0..00000000 --- a/app/lib/Functions/convertId.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertId = void 0; -const item_helpers_1 = require("../Helpers/item_helpers"); -function convertId(id, stringMethod) { - try { - if (typeof id === "string") { - return (0, item_helpers_1.convertStringId)(id); - } - else { - return id.toString(stringMethod || "hex"); - } - } - catch (err) { - throw new Error(`WeivData - Error when converting an ID: ${err}`); - } -} -exports.convertId = convertId; diff --git a/app/lib/Functions/flushCache.js b/app/lib/Functions/flushCache.js deleted file mode 100644 index b878c848..00000000 --- a/app/lib/Functions/flushCache.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.flushCache = void 0; -const permission_helpers_1 = require("../Connection/permission_helpers"); -const get_1 = require("../Functions/get"); -const isReferenced_1 = require("../Functions/isReferenced"); -const secret_helpers_1 = require("../Helpers/secret_helpers"); -const automatic_connection_provider_1 = require("../Connection/automatic_connection_provider"); -const cacheSelections = { - "permissions": permission_helpers_1.getPermissionsCache, - "get": get_1.getGetCache, - "isreferenced": isReferenced_1.getIsReferencedCache, - "helpersecrets": secret_helpers_1.getHelperSecretsCache, - "connectionclients": automatic_connection_provider_1.getClientCache, - "secrets": secret_helpers_1.getHelperSecretsCache -}; -function flushCache(filters) { - try { - const cachesToFlush = []; - if (filters) { - if (filters.length > 0) { - for (const filter of filters) { - const cacheValue = cacheSelections[filter](); - cachesToFlush.push(cacheValue); - } - } - else { - for (const key of Object.keys(cacheSelections)) { - const cacheValue = cacheSelections[key](); - cachesToFlush.push(cacheValue); - } - } - } - for (const key of Object.keys(cacheSelections)) { - const cacheValue = cacheSelections[key](); - cachesToFlush.push(cacheValue); - } - for (const cacheData of cachesToFlush) { - cacheData.flushAll(); - } - } - catch (err) { - throw new Error(`WeivData - Error when flushing caches! ${err}`); - } -} -exports.flushCache = flushCache; diff --git a/app/lib/Functions/get.js b/app/lib/Functions/get.js deleted file mode 100644 index c932f9ce..00000000 --- a/app/lib/Functions/get.js +++ /dev/null @@ -1,86 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getGetCache = exports.get = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const node_cache_1 = __importDefault(require("node-cache")); -const hook_manager_1 = require("../Hooks/hook_manager"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const validator_1 = require("../Helpers/validator"); -const cache = new node_cache_1.default({ - checkperiod: 5, - useClones: false, - deleteOnExpire: true -}); -async function get(collectionId, itemId, options) { - try { - const { safeOptions, safeItemId } = await (0, validator_1.validateParams)({ collectionId, itemId, options }, ["collectionId", "itemId"], "get"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, enableCache, cacheTimeout } = safeOptions || {}; - let editedItemId; - if (suppressHooks != true) { - editedItemId = await (0, hook_manager_1.runDataHook)(collectionId, "beforeGet", [safeItemId, context]).catch((err) => { - throw new Error(`beforeGet Hook Failure ${err}`); - }); - } - let newItemId = safeItemId; - if (editedItemId) { - newItemId = (0, item_helpers_1.convertStringId)(editedItemId); - } - if (enableCache) { - const cacheKey = `${collectionId}-${safeItemId.toHexString()}-${options ? JSON.stringify(options) : "{}"}`; - const cachedItem = cache.get(cacheKey); - if (cachedItem && !editedItemId) { - return cachedItem; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const item = await collection.findOne({ _id: newItemId }, { readConcern }); - if (item) { - if (suppressHooks != true) { - let editedItem = await (0, hook_manager_1.runDataHook)(collectionId, 'afterGet', [item, context]).catch((err) => { - throw new Error(`afterGet Hook Failure ${err}`); - }); - if (editedItem) { - if (editedItem._id) { - editedItem._id = (0, item_helpers_1.convertObjectId)(editedItem._id); - } - if (enableCache) { - cache.set(`${collectionId}-${safeItemId.toHexString()}-${options ? JSON.stringify(options) : "{}"}`, editedItem, cacheTimeout || 15); - } - return editedItem; - } - } - if (item._id) { - const _id = (0, item_helpers_1.convertObjectId)(item._id); - if (enableCache) { - cache.set(`${collectionId}-${safeItemId.toHexString()}-${options ? JSON.stringify(options) : "{}"}`, { ...item, _id }, cacheTimeout || 15); - } - return { - ...item, - _id - }; - } - else { - if (enableCache) { - cache.set(`${collectionId}-${safeItemId.toHexString()}-${options ? JSON.stringify(options) : "{}"}`, item, cacheTimeout || 15); - } - return item; - } - } - else { - return null; - } - } - catch (err) { - throw new Error(`WeivData - Error when trying to get item from the collectin by itemId: ${err}`); - } -} -exports.get = get; -function getGetCache() { - return cache; -} -exports.getGetCache = getGetCache; diff --git a/app/lib/Functions/increment.js b/app/lib/Functions/increment.js deleted file mode 100644 index 191c3a5e..00000000 --- a/app/lib/Functions/increment.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.increment = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const validator_1 = require("../Helpers/validator"); -async function increment(collectionId, itemId, propertyName, value, options) { - try { - const { safeOptions } = await (0, validator_1.validateParams)({ collectionId, itemId, propertyName, value, options }, ["collectionId", "itemId", "propertyName", "value"], "increment"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern } = safeOptions || {}; - let editedModify = { propertyName, value }; - if (suppressHooks != true) { - const modifiedParams = await (0, hook_manager_1.runDataHook)(collectionId, "beforeIncrement", [{ propertyName, value }, context]).catch((err) => { - throw new Error(`beforeIncrement Hook Failure ${err}`); - }); - if (modifiedParams) { - editedModify = modifiedParams; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const item = await collection.findOneAndUpdate({ _id: (0, item_helpers_1.convertStringId)(itemId) }, { $inc: { [editedModify.propertyName]: editedModify.value } }, { readConcern, returnDocument: "after", includeResultMetadata: false }); - if (item) { - if (suppressHooks != true) { - const modifiedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterIncrement", [item, context]).catch((err) => { - throw new Error(`afterIncrement Hook Failure ${err}`); - }); - if (modifiedResult) { - if (modifiedResult._id) { - modifiedResult._id = (0, item_helpers_1.convertObjectId)(modifiedResult._id); - } - return modifiedResult; - } - } - if (item._id) { - return { - ...item, - _id: (0, item_helpers_1.convertObjectId)(item._id) - }; - } - else { - return item; - } - } - else { - return null; - } - } - catch (err) { - throw new Error(`WeivData - Error when incrementing a filed in an item: ${err}`); - } -} -exports.increment = increment; diff --git a/app/lib/Functions/insert.js b/app/lib/Functions/insert.js deleted file mode 100644 index 291aee43..00000000 --- a/app/lib/Functions/insert.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.insert = void 0; -const lodash_1 = require("lodash"); -const member_id_helpers_1 = require("../Helpers/member_id_helpers"); -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const validator_1 = require("../Helpers/validator"); -const item_helpers_1 = require("../Helpers/item_helpers"); -async function insert(collectionId, item, options) { - try { - const { safeItem, safeOptions } = await (0, validator_1.validateParams)({ collectionId, item, options }, ["collectionId", "item"], "insert"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, enableVisitorId, readConcern } = safeOptions || {}; - const defaultValues = { - _updatedDate: new Date(), - _createdDate: new Date(), - }; - defaultValues["_owner"] = await (0, member_id_helpers_1.getOwnerId)(enableVisitorId); - const modifiedItem = (0, lodash_1.merge)(defaultValues, safeItem); - let editedItem; - if (suppressHooks != true) { - editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeInsert", [modifiedItem, context]).catch((err) => { - throw new Error(`beforeInsert Hook Failure ${err}`); - }); - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { insertedId, acknowledged } = await collection.insertOne(!editedItem ? modifiedItem : editedItem, { readConcern }); - if (acknowledged) { - if (suppressHooks != true) { - const editedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterInsert", [{ ...!editedItem ? modifiedItem : editedItem, _id: insertedId }, context]).catch((err) => { - throw new Error(`afterInsert Hook Failure ${err}`); - }); - if (editedResult) { - if (editedResult._id) { - editedResult._id = (0, item_helpers_1.convertObjectId)(editedResult._id); - } - return editedResult; - } - } - const item = { ...!editedItem ? modifiedItem : editedItem, _id: insertedId }; - if (item._id) { - return { - ...item, - _id: (0, item_helpers_1.convertObjectId)(item._id) - }; - } - else { - return item; - } - } - else { - throw new Error(`acknowledged: ${acknowledged}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when inserting an item into a collection: ${err}`); - } -} -exports.insert = insert; diff --git a/app/lib/Functions/insertReference.js b/app/lib/Functions/insertReference.js deleted file mode 100644 index a66fb261..00000000 --- a/app/lib/Functions/insertReference.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.insertReference = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const validator_1 = require("../Helpers/validator"); -async function insertReference(collectionId, propertyName, referringItem, referencedItem, options) { - try { - const { safeReferencedItemIds, safeReferringItemId, safeOptions } = await (0, validator_1.validateParams)({ collectionId, propertyName, referringItem, referencedItem, options }, ["collectionId", "propertyName", "referringItem", "referencedItem"], "insertReference"); - const { suppressAuth, readConcern } = safeOptions || {}; - const references = safeReferencedItemIds; - const itemId = safeReferringItemId; - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { acknowledged, modifiedCount } = await collection.updateOne({ _id: itemId }, { $push: { [propertyName]: { $each: references } }, $set: { _updatedDate: new Date() } }, { readConcern }); - if (!acknowledged || modifiedCount <= 0) { - throw new Error(`acknowledged: ${acknowledged}, modifiedCount: ${modifiedCount}`); - } - } - catch (err) { - throw new Error(`Error when inserting a reference item into an item: ${err}`); - } -} -exports.insertReference = insertReference; diff --git a/app/lib/Functions/isReferenced.js b/app/lib/Functions/isReferenced.js deleted file mode 100644 index 6ab05126..00000000 --- a/app/lib/Functions/isReferenced.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getIsReferencedCache = exports.isReferenced = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const validator_1 = require("../Helpers/validator"); -const node_cache_1 = __importDefault(require("node-cache")); -const cache = new node_cache_1.default({ - checkperiod: 5, - useClones: false, - deleteOnExpire: true -}); -async function isReferenced(collectionId, propertyName, referringItem, referencedItem, options) { - try { - const { safeReferencedItemIds, safeReferringItemId, safeOptions } = await (0, validator_1.validateParams)({ collectionId, propertyName, referencedItem, referringItem, options }, ["collectionId", "propertyName", "referringItem", "referencedItem"], "isReferenced"); - const { suppressAuth, readConcern, enableCache, cacheTimeout } = safeOptions || {}; - const cacheKey = `${collectionId}-${propertyName}-${referringItem}-${referencedItem}-${options ? JSON.stringify(options) : "{}"}`; - if (enableCache) { - const cachedItem = cache.get(cacheKey); - if (cachedItem) { - return cachedItem; - } - } - const references = safeReferencedItemIds; - const itemId = safeReferringItemId; - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const totalCount = await collection.countDocuments({ _id: itemId, [propertyName]: { $in: references } }, { readConcern }); - if (totalCount > 0) { - if (enableCache) { - cache.set(cacheKey, true, cacheTimeout || 15); - } - return true; - } - else { - if (enableCache) { - cache.set(cacheKey, false, cacheTimeout || 15); - } - return false; - } - } - catch (err) { - throw new Error(`WeivData - Error when checking if item is referenced: ${err}`); - } -} -exports.isReferenced = isReferenced; -function getIsReferencedCache() { - return cache; -} -exports.getIsReferencedCache = getIsReferencedCache; diff --git a/app/lib/Functions/multiply.js b/app/lib/Functions/multiply.js deleted file mode 100644 index 4098b782..00000000 --- a/app/lib/Functions/multiply.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.multiply = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const validator_1 = require("../Helpers/validator"); -async function multiply(collectionId, itemId, propertyName, value, options) { - try { - const { safeOptions } = await (0, validator_1.validateParams)({ collectionId, itemId, propertyName, value, options }, ["collectionId", "itemId", "value", "propertyName"], "multiply"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern } = safeOptions || {}; - let editedModify = { propertyName, value }; - if (suppressHooks != true) { - const modifiedParams = await (0, hook_manager_1.runDataHook)(collectionId, "beforeMultiply", [{ propertyName, value }, context]).catch((err) => { - throw new Error(`beforeMultiply Hook Failure ${err}`); - }); - if (modifiedParams) { - editedModify = modifiedParams; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const item = await collection.findOneAndUpdate({ _id: (0, item_helpers_1.convertStringId)(itemId) }, { $mul: { [editedModify.propertyName]: editedModify.value } }, { readConcern, returnDocument: "after", includeResultMetadata: false }); - if (item) { - if (suppressHooks != true) { - const modifiedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterMultiply", [item, context]).catch((err) => { - throw new Error(`afterMultiply Hook Failure ${err}`); - }); - if (modifiedResult) { - if (modifiedResult._id) { - modifiedResult._id = (0, item_helpers_1.convertObjectId)(modifiedResult._id); - } - return modifiedResult; - } - } - if (item._id) { - return { - ...item, - _id: (0, item_helpers_1.convertObjectId)(item._id) - }; - } - else { - return item; - } - } - else { - return null; - } - } - catch (err) { - throw new Error(`WeivData - Error when multiplying a filed in an item: ${err}`); - } -} -exports.multiply = multiply; diff --git a/app/lib/Functions/native.js b/app/lib/Functions/native.js deleted file mode 100644 index da143b61..00000000 --- a/app/lib/Functions/native.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.native = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const validator_1 = require("../Helpers/validator"); -async function native(collectionId, suppressAuth) { - try { - await (0, validator_1.validateParams)({ collectionId }, ["collectionId"], "native"); - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - return collection; - } - catch (err) { - throw new Error(`WeivData - Error when returning native collection cursor from mongodb driver: ${err}`); - } -} -exports.native = native; diff --git a/app/lib/Functions/pull.js b/app/lib/Functions/pull.js deleted file mode 100644 index a54a5756..00000000 --- a/app/lib/Functions/pull.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.pull = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const validator_1 = require("../Helpers/validator"); -async function pull(collectionId, itemId, propertyName, value, options) { - try { - const { safeValue, safeOptions } = await (0, validator_1.validateParams)({ collectionId, itemId, propertyName, value, options }, ["collectionId", "itemId", "value", "propertyName"], "pull"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern } = safeOptions || {}; - let editedModify = { propertyName, value: safeValue }; - if (suppressHooks != true) { - const modifiedParams = await (0, hook_manager_1.runDataHook)(collectionId, "beforePull", [{ propertyName, value: safeValue }, context]).catch((err) => { - throw new Error(`beforePull Hook Failure ${err}`); - }); - if (modifiedParams) { - editedModify = modifiedParams; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const item = await collection.findOneAndUpdate({ _id: (0, item_helpers_1.convertStringId)(itemId) }, { $pull: { [editedModify.propertyName]: editedModify.value } }, { readConcern, returnDocument: "after", includeResultMetadata: false }); - if (item) { - if (suppressHooks != true) { - const modifiedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterPull", [item, context]).catch((err) => { - throw new Error(`afterPull Hook Failure ${err}`); - }); - if (modifiedResult) { - if (modifiedResult._id) { - modifiedResult._id = (0, item_helpers_1.convertObjectId)(modifiedResult._id); - } - return modifiedResult; - } - } - if (item._id) { - return { - ...item, - _id: (0, item_helpers_1.convertObjectId)(item._id) - }; - } - else { - return item; - } - } - else { - return null; - } - } - catch (err) { - throw new Error(`WeivData - Error when removıng (pullıng) value/s from an array filed in an item: ${err}`); - } -} -exports.pull = pull; diff --git a/app/lib/Functions/push.js b/app/lib/Functions/push.js deleted file mode 100644 index 370bfded..00000000 --- a/app/lib/Functions/push.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.push = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const validator_1 = require("../Helpers/validator"); -async function push(collectionId, itemId, propertyName, value, options) { - try { - const { safeValue, safeOptions } = await (0, validator_1.validateParams)({ collectionId, itemId, propertyName, value, options }, ["collectionId", "itemId", "propertyName", "value"], "push"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern } = safeOptions || {}; - let editedModify = { propertyName, value: safeValue }; - if (suppressHooks != true) { - const modifiedParams = await (0, hook_manager_1.runDataHook)(collectionId, "beforePush", [{ propertyName, value: safeValue }, context]).catch((err) => { - throw new Error(`beforePush Hook Failure ${err}`); - }); - if (modifiedParams) { - editedModify = modifiedParams; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const item = await collection.findOneAndUpdate({ _id: (0, item_helpers_1.convertStringId)(itemId) }, { $push: { [editedModify.propertyName]: editedModify.value } }, { readConcern, returnDocument: "after", includeResultMetadata: false }); - if (item) { - if (suppressHooks != true) { - const modifiedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterPush", [item, context]).catch((err) => { - throw new Error(`afterPush Hook Failure ${err}`); - }); - if (modifiedResult) { - if (modifiedResult._id) { - modifiedResult._id = (0, item_helpers_1.convertObjectId)(modifiedResult._id); - } - return modifiedResult; - } - } - if (item._id) { - return { - ...item, - _id: (0, item_helpers_1.convertObjectId)(item._id) - }; - } - else { - return item; - } - } - else { - return null; - } - } - catch (err) { - throw new Error(`WeivData - Error when inserting (pushing) new value/s into an array filed in an item: ${err}`); - } -} -exports.push = push; diff --git a/app/lib/Functions/remove.js b/app/lib/Functions/remove.js deleted file mode 100644 index bf950bfe..00000000 --- a/app/lib/Functions/remove.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.remove = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const validator_1 = require("../Helpers/validator"); -const member_id_helpers_1 = require("../Helpers/member_id_helpers"); -async function remove(collectionId, itemId, options) { - try { - const { safeItemId, safeOptions } = await (0, validator_1.validateParams)({ collectionId, itemId, options }, ["collectionId", "itemId"], "remove"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, onlyOwner } = safeOptions || {}; - let editedItemId; - if (suppressHooks != true) { - editedItemId = await (0, hook_manager_1.runDataHook)(collectionId, "beforeRemove", [safeItemId, context]).catch((err) => { - throw new Error(`beforeRemove Hook Failure ${err}`); - }); - } - let newItemId = safeItemId; - if (editedItemId) { - newItemId = (0, item_helpers_1.convertStringId)(editedItemId); - } - const filter = { _id: newItemId }; - if (onlyOwner) { - const currentMemberId = await (0, member_id_helpers_1.getOwnerId)(); - if (currentMemberId) { - filter._owner = currentMemberId; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const item = await collection.findOneAndDelete(filter, { readConcern, includeResultMetadata: false }); - if (item) { - if (suppressHooks != true) { - let editedItem = await (0, hook_manager_1.runDataHook)(collectionId, 'afterRemove', [item, context]).catch((err) => { - throw new Error(`afterRemove Hook Failure ${err}`); - }); - if (editedItem) { - if (editedItem._id) { - editedItem._id = (0, item_helpers_1.convertObjectId)(editedItem._id); - } - return editedItem; - } - } - if (item._id) { - return { - ...item, - _id: (0, item_helpers_1.convertObjectId)(item._id) - }; - } - else { - return item; - } - } - else { - return null; - } - } - catch (err) { - throw new Error(`WeivData - Error when removing an item from collection: ${err}`); - } -} -exports.remove = remove; diff --git a/app/lib/Functions/removeReference.js b/app/lib/Functions/removeReference.js deleted file mode 100644 index acad2a84..00000000 --- a/app/lib/Functions/removeReference.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.removeReference = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const validator_1 = require("../Helpers/validator"); -async function removeReference(collectionId, propertyName, referringItem, referencedItem, options) { - try { - const { safeOptions, safeReferencedItemIds, safeReferringItemId } = await (0, validator_1.validateParams)({ collectionId, propertyName, referringItem, referencedItem, options }, ["collectionId", "propertyName", "referringItem", "referencedItem"], "removeReference"); - const { suppressAuth, readConcern } = safeOptions || {}; - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { acknowledged, modifiedCount } = await collection.updateOne({ _id: safeReferringItemId }, { $pull: { [propertyName]: { $in: safeReferencedItemIds } }, $set: { _updatedDate: new Date() } }, { readConcern }); - if (!acknowledged || modifiedCount <= 0) { - throw new Error(`acknowledged: ${acknowledged}, modifiedCount: ${modifiedCount}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when removing references: ${err}`); - } -} -exports.removeReference = removeReference; diff --git a/app/lib/Functions/replace.js b/app/lib/Functions/replace.js deleted file mode 100644 index 5941155c..00000000 --- a/app/lib/Functions/replace.js +++ /dev/null @@ -1,63 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.replace = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const validator_1 = require("../Helpers/validator"); -const member_id_helpers_1 = require("../Helpers/member_id_helpers"); -async function replace(collectionId, item, options) { - try { - const { safeItem, safeOptions } = await (0, validator_1.validateParams)({ collectionId, item, options }, ["collectionId", "item"], "replace"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, onlyOwner } = safeOptions || {}; - let editedItem; - if (suppressHooks != true) { - editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeReplace", [safeItem, context]).catch((err) => { - throw new Error(`beforeReplace Hook Failure ${err}`); - }); - } - const itemId = !editedItem ? (0, item_helpers_1.convertStringId)(safeItem._id) : (0, item_helpers_1.convertStringId)(editedItem._id); - const replaceItem = !editedItem ? safeItem : editedItem; - delete replaceItem._id; - const filter = { _id: itemId }; - if (onlyOwner) { - const currentMemberId = await (0, member_id_helpers_1.getOwnerId)(); - if (currentMemberId) { - filter._owner = currentMemberId; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const value = await collection.findOneAndReplace(filter, { ...replaceItem, _updatedDate: new Date() }, { readConcern, returnDocument: "after", includeResultMetadata: false }); - if (value) { - if (suppressHooks != true) { - let editedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterReplace", [value, context]).catch((err) => { - throw new Error(`afterReplace Hook Failure ${err}`); - }); - if (editedResult) { - if (editedResult._id) { - editedResult._id = (0, item_helpers_1.convertObjectId)(editedResult._id); - } - return editedResult; - } - } - if (value._id) { - return { - ...value, - _id: (0, item_helpers_1.convertObjectId)(value._id) - }; - } - else { - return value; - } - } - else { - throw new Error(`returned value has problem value: ${value}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when replacing an item: ${err}`); - } -} -exports.replace = replace; diff --git a/app/lib/Functions/replaceReferences.js b/app/lib/Functions/replaceReferences.js deleted file mode 100644 index 2e67c34b..00000000 --- a/app/lib/Functions/replaceReferences.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.replaceReferences = void 0; -const validator_1 = require("../Helpers/validator"); -const update_1 = require("./update"); -async function replaceReferences(collectionId, propertyName, referringItem, referencedItem, options) { - try { - const { safeOptions, safeReferringItemId, safeReferencedItemIds } = await (0, validator_1.validateParams)({ collectionId, propertyName, referringItem, referencedItem, options }, ["collectionId", "propertyName", "referringItem", "referencedItem"], "replaceReferences"); - const updated = await (0, update_1.update)(collectionId, { _id: safeReferringItemId, [propertyName]: safeReferencedItemIds }, safeOptions); - if (!updated) { - throw new Error(`couldn't replace references: ${updated}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when replacing references, ${err}`); - } -} -exports.replaceReferences = replaceReferences; diff --git a/app/lib/Functions/save.js b/app/lib/Functions/save.js deleted file mode 100644 index 24327ac7..00000000 --- a/app/lib/Functions/save.js +++ /dev/null @@ -1,92 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.save = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const mongodb_1 = require("mongodb"); -const validator_1 = require("../Helpers/validator"); -const member_id_helpers_1 = require("../Helpers/member_id_helpers"); -async function save(collectionId, item, options) { - try { - const { safeOptions, safeItem } = await (0, validator_1.validateParams)({ collectionId, item, options }, ["collectionId", "item"], "save"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, onlyOwner, enableVisitorId } = safeOptions || {}; - let editedItem; - if (safeItem._id && typeof safeItem._id === "string") { - safeItem._id = (0, item_helpers_1.convertStringId)(safeItem._id); - if (suppressHooks != true) { - editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeUpdate", [safeItem, context]).catch((err) => { - throw new Error(`beforeUpdate (save) Hook Failure ${err}`); - }); - } - } - else { - safeItem._owner = await (0, member_id_helpers_1.getOwnerId)(enableVisitorId); - if (suppressHooks != true) { - editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeInsert", [safeItem, context]).catch((err) => { - throw new Error(`beforeInsert (save) Hook Failure ${err}`); - }); - } - } - editedItem = { - ...safeItem, - ...editedItem - }; - let filter; - if (safeItem._id && typeof safeItem._id === "string" && onlyOwner) { - filter = { _id: editedItem._id }; - const currentMemberId = await (0, member_id_helpers_1.getOwnerId)(enableVisitorId); - if (currentMemberId) { - filter._owner = currentMemberId; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { upsertedId, acknowledged } = await collection.updateOne(filter ? filter : { _id: new mongodb_1.ObjectId() }, { $set: { ...editedItem, _updatedDate: new Date() }, $setOnInsert: !editedItem._createdDate ? { _createdDate: new Date() } : {} }, { readConcern, upsert: true }); - const returnedItem = { ...editedItem, _id: editedItem._id }; - if (acknowledged) { - if (upsertedId) { - const editedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterInsert", [returnedItem, context]).catch((err) => { - throw new Error(`afterInsert Hook Failure ${err}`); - }); - if (editedResult) { - if (editedResult._id) { - editedResult._id = (0, item_helpers_1.convertObjectId)(editedResult._id); - } - return { item: editedResult, upsertedId }; - } - else { - if (returnedItem._id) { - returnedItem._id = (0, item_helpers_1.convertObjectId)(returnedItem._id); - } - return { item: returnedItem, upsertedId }; - } - } - else { - const editedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterUpdate", [returnedItem, context]).catch((err) => { - throw new Error(`afterUpdate Hook Failure ${err}`); - }); - if (editedResult) { - if (editedResult._id) { - editedResult._id = (0, item_helpers_1.convertObjectId)(editedResult._id); - } - return { item: editedResult }; - } - else { - if (returnedItem._id) { - returnedItem._id = (0, item_helpers_1.convertObjectId)(returnedItem._id); - } - return { item: returnedItem }; - } - } - } - else { - throw new Error(`acknowledged: ${acknowledged}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when saving an item to collection: ${err}`); - } -} -exports.save = save; diff --git a/app/lib/Functions/truncate.js b/app/lib/Functions/truncate.js deleted file mode 100644 index 9463bad2..00000000 --- a/app/lib/Functions/truncate.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.truncate = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const validator_1 = require("../Helpers/validator"); -async function truncate(collectionId, options) { - try { - const { safeOptions } = await (0, validator_1.validateParams)({ collectionId, options }, ["collectionId"], "truncate"); - const { suppressAuth } = safeOptions || {}; - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const { acknowledged } = await collection.deleteMany({}); - if (acknowledged) { - return true; - } - else { - throw new Error(`couldn't remove all items in the collection, acknowledged: ${acknowledged}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when removing all items in a collection (truncate): ${err}`); - } -} -exports.truncate = truncate; diff --git a/app/lib/Functions/update.js b/app/lib/Functions/update.js deleted file mode 100644 index ef976977..00000000 --- a/app/lib/Functions/update.js +++ /dev/null @@ -1,63 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.update = void 0; -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const item_helpers_1 = require("../Helpers/item_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const validator_1 = require("../Helpers/validator"); -const member_id_helpers_1 = require("../Helpers/member_id_helpers"); -async function update(collectionId, item, options) { - try { - const { safeItem, safeOptions } = await (0, validator_1.validateParams)({ collectionId, item, options }, ["collectionId", "item"], "update"); - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - const { suppressAuth, suppressHooks, readConcern, onlyOwner } = safeOptions || {}; - let editedItem; - if (suppressHooks != true) { - editedItem = await (0, hook_manager_1.runDataHook)(collectionId, "beforeUpdate", [safeItem, context]).catch((err) => { - throw new Error(`beforeUpdate Hook Failure ${err}`); - }); - } - const itemId = !editedItem ? (0, item_helpers_1.convertStringId)(safeItem._id) : (0, item_helpers_1.convertStringId)(editedItem._id); - const updateItem = !editedItem ? safeItem : editedItem; - delete updateItem._id; - const filter = { _id: itemId }; - if (onlyOwner) { - const currentMemberId = await (0, member_id_helpers_1.getOwnerId)(); - if (currentMemberId) { - filter._owner = currentMemberId; - } - } - const { collection } = await (0, connection_helpers_1.connectionHandler)(collectionId, suppressAuth); - const value = await collection.findOneAndUpdate(filter, { $set: { ...updateItem, _updatedDate: new Date() } }, { readConcern, returnDocument: "after", includeResultMetadata: false }); - if (value) { - if (suppressHooks != true) { - let editedResult = await (0, hook_manager_1.runDataHook)(collectionId, "afterUpdate", [value, context]).catch((err) => { - throw new Error(`afterUpdate Hook Failure ${err}`); - }); - if (editedResult) { - if (editedResult._id) { - editedResult._id = (0, item_helpers_1.convertObjectId)(editedResult._id); - } - return editedResult; - } - } - if (value._id) { - return { - ...value, - _id: (0, item_helpers_1.convertObjectId)(value._id) - }; - } - else { - return value; - } - } - else { - throw new Error(`returned value has problem value: ${value}`); - } - } - catch (err) { - throw new Error(`WeivData - Error when updating an item: ${err}`); - } -} -exports.update = update; diff --git a/app/lib/Helpers/connection_helpers.js b/app/lib/Helpers/connection_helpers.js deleted file mode 100644 index a0243e9e..00000000 --- a/app/lib/Helpers/connection_helpers.js +++ /dev/null @@ -1,82 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getCustomCacheRules = exports.loadConnectionOptions = exports.connectionHandler = void 0; -const customConnectionOptions = __importStar(require("../../../../../../../../../user-code/backend/WeivData/connection-options")); -const automatic_connection_provider_1 = require("../Connection/automatic_connection_provider"); -const name_helpers_1 = require("./name_helpers"); -async function connectionHandler(collectionId, suppressAuth = false) { - try { - let db; - const { dbName, collectionName } = (0, name_helpers_1.splitCollectionId)(collectionId); - const { pool, memberId } = await (0, automatic_connection_provider_1.useClient)(suppressAuth); - if (dbName && typeof dbName === "string") { - db = pool.db(dbName); - } - else { - db = pool.db("ExWeiv"); - } - return { memberId, database: db, collection: db.collection(collectionName) }; - } - catch (err) { - throw new Error(`when trying to connect to database via useClient and Mongo Client ${err}`); - } -} -exports.connectionHandler = connectionHandler; -async function loadConnectionOptions(role) { - try { - if (typeof role !== "string") { - throw new Error("type of role is not string!"); - } - const customOptions = customConnectionOptions[role]; - if (customOptions) { - return await customOptions(); - } - else { - return { - tls: true, - }; - } - } - catch (err) { - throw new Error(`when returning options for MongoDB Client connection: ${err}`); - } -} -exports.loadConnectionOptions = loadConnectionOptions; -async function getCustomCacheRules() { - try { - const cacheRules = customConnectionOptions["clientCacheRules"]; - if (cacheRules) { - return await cacheRules(); - } - else { - return { useClones: false, stdTTL: 5 * 60, deleteOnExpire: true }; - } - } - catch (err) { - throw new Error(`when loading custom cache rules for MongoClient connections, err: ${err}`); - } -} -exports.getCustomCacheRules = getCustomCacheRules; diff --git a/app/lib/Helpers/encrypt_helpers.js b/app/lib/Helpers/encrypt_helpers.js deleted file mode 100644 index 9e4895b6..00000000 --- a/app/lib/Helpers/encrypt_helpers.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getSecretKey = void 0; -const wix_secrets_backend_v2_1 = require("wix-secrets-backend.v2"); -const crypto_1 = __importDefault(require("crypto")); -const secret_helpers_1 = require("./secret_helpers"); -async function getSecretKey() { - try { - const cachedSecret = await (0, secret_helpers_1.getCachedSecret)("WeivDataURIEncryptSecret"); - if (cachedSecret) { - return cachedSecret; - } - else { - const secret = { - name: "WeivDataURIEncryptSecret", - value: crypto_1.default.randomBytes(32).toString('hex'), - description: "This is a secret key that's used when we are storing uris in cache to keep them secure. If you delete it system will create new one. Do not delete it!" - }; - await wix_secrets_backend_v2_1.secrets.createSecret(secret); - return secret.value; - } - } - catch (err) { - throw new Error(`Error when creating or getting URI secret key: ${err}`); - } -} -exports.getSecretKey = getSecretKey; diff --git a/app/lib/Helpers/hook_helpers.js b/app/lib/Helpers/hook_helpers.js deleted file mode 100644 index 0b906973..00000000 --- a/app/lib/Helpers/hook_helpers.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.prepareHookContext = void 0; -const wix_users_backend_1 = require("wix-users-backend"); -const name_helpers_1 = require("./name_helpers"); -function prepareHookContext(collectionId) { - const { dbName, collectionName } = (0, name_helpers_1.splitCollectionId)(collectionId); - const roles = wix_users_backend_1.currentUser.getRoles(); - if (wix_users_backend_1.currentUser.loggedIn) { - return { - dbName, - collectionName, - userId: wix_users_backend_1.currentUser.id, - userRoles: roles - }; - } - else { - return { - dbName, - collectionName, - userRoles: roles - }; - } -} -exports.prepareHookContext = prepareHookContext; diff --git a/app/lib/Helpers/item_helpers.js b/app/lib/Helpers/item_helpers.js deleted file mode 100644 index 55b33d6e..00000000 --- a/app/lib/Helpers/item_helpers.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertObjectId = exports.convertStringId = void 0; -const mongodb_1 = require("mongodb"); -function convertStringId(_id, create = false) { - if (!_id) { - throw new Error(`_id doesn't exist and it's undefined!`); - } - else { - if (typeof _id !== "string" && typeof _id !== "object") { - throw new Error(`Invalid _id value type!, it must be a string or ObjectId`); - } - } - if (mongodb_1.ObjectId.isValid(_id)) { - if (typeof _id === "string") { - return new mongodb_1.ObjectId(_id); - } - else if (typeof _id === "object") { - return _id; - } - else { - throw new Error(`Invalid ObjectID (converted from string or ObjectId but it's still invalid)`); - } - } - else { - if (create === true) { - return new mongodb_1.ObjectId(); - } - throw new Error(`Invalid _id type for convertStringId method, itemIds should be string or ObjectId!`); - } -} -exports.convertStringId = convertStringId; -function convertObjectId(_id) { - if (_id) { - if (typeof _id === "string") { - return _id; - } - return _id.toHexString(); - } - else { - throw new Error(`WeivData - ObjectId -> String converter not working!`); - } -} -exports.convertObjectId = convertObjectId; diff --git a/app/lib/Helpers/member_id_helpers.js b/app/lib/Helpers/member_id_helpers.js deleted file mode 100644 index 84687e71..00000000 --- a/app/lib/Helpers/member_id_helpers.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getOwnerId = void 0; -const wix_data_1 = __importDefault(require("wix-data")); -const wix_users_backend_1 = require("wix-users-backend"); -async function getOwnerId(enableVisitorId = false) { - try { - if (wix_users_backend_1.currentUser.loggedIn) { - return wix_users_backend_1.currentUser.id; - } - else if (enableVisitorId === true) { - const { _owner, _id } = await wix_data_1.default.insert("WeivOwnerID", {}, { supressAuth: true }); - wix_data_1.default.remove("WeivOwnerID", _id, { suppressAuth: true }); - return _owner; - } - else { - return null; - } - } - catch (err) { - throw new Error(`Error when checking user id: (Possible Velo API BUG) ${err}`); - } -} -exports.getOwnerId = getOwnerId; diff --git a/app/lib/Helpers/name_helpers.js b/app/lib/Helpers/name_helpers.js deleted file mode 100644 index 38acdaa0..00000000 --- a/app/lib/Helpers/name_helpers.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.splitCollectionId = void 0; -const lodash_1 = require("lodash"); -exports.splitCollectionId = (0, lodash_1.memoize)(splitCollectionIdMain); -function splitCollectionIdMain(collectionId) { - if (!collectionId || typeof collectionId !== "string") { - throw new Error(`CollectionID is Required with this syntax: / and it must be a string!`); - } - const [dbName, collectionName] = collectionId.split('/'); - if (!dbName || !collectionName) { - return { dbName: "ExWeiv", collectionName: dbName }; - } - return { dbName, collectionName }; -} diff --git a/app/lib/Helpers/query_referenced_helpers.js b/app/lib/Helpers/query_referenced_helpers.js deleted file mode 100644 index 30bff3d4..00000000 --- a/app/lib/Helpers/query_referenced_helpers.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getPipeline = void 0; -const name_helpers_1 = require("./name_helpers"); -function getPipeline(itemId, targetCollectionId, propertyName, pipelineOptions) { - if (typeof itemId !== "object" || typeof targetCollectionId !== "string" || typeof propertyName !== "string" || typeof pipelineOptions !== "object") { - throw new Error("one or multiple parameter type is wrong!"); - } - const { collectionName } = (0, name_helpers_1.splitCollectionId)(targetCollectionId); - return [ - { - $match: { - _id: itemId, - }, - }, - { - $sort: { - [propertyName]: pipelineOptions.order === 'asc' ? 1 : -1 - } - }, - { - $lookup: { - from: collectionName, - localField: propertyName, - foreignField: "_id", - as: "referencedItems", - }, - }, - { - $project: { - referencedItems: 1, - totalItems: { $size: `$${propertyName}` }, - }, - }, - { - $addFields: { - referencedItemIds: { - $slice: ["$referencedItems._id", pipelineOptions.skip, pipelineOptions.pageSize], - }, - }, - }, - { - $addFields: { - referencedItems: { - $filter: { - input: "$referencedItems", - as: "item", - cond: { - $in: [ - "$$item._id", - "$referencedItemIds", - ], - }, - }, - }, - }, - }, - { - $project: { - referencedItems: 1, - totalItems: 1, - }, - }, - ]; -} -exports.getPipeline = getPipeline; diff --git a/app/lib/Helpers/reference_helpers.js b/app/lib/Helpers/reference_helpers.js deleted file mode 100644 index b58af81b..00000000 --- a/app/lib/Helpers/reference_helpers.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getReferencesItemIds = exports.getReferenceItemId = void 0; -const item_helpers_1 = require("./item_helpers"); -const mongodb_1 = require("mongodb"); -const validator_1 = require("./validator"); -const lodash_1 = require("lodash"); -const getReferenceItemId = (referringItem) => { - if (referringItem) { - let safeReferringItem; - if (mongodb_1.ObjectId.isValid(referringItem)) { - if (typeof referringItem === "string") { - return new mongodb_1.ObjectId(referringItem); - } - else if (typeof referringItem === "object") { - return referringItem; - } - else { - throw new Error(`ItemID is not a string or ObjectID so we can't convert it to ObjectID in any way`); - } - } - else { - if (typeof referringItem === "object") { - if (!referringItem._id) { - throw new Error(`when sending Item it must contain _id field in it with a valid value!`); - } - safeReferringItem = (0, validator_1.copyOwnPropsOnly)(referringItem); - return (0, item_helpers_1.convertStringId)(safeReferringItem._id); - } - else { - if (typeof referringItem !== "string") { - throw new Error(`ItemID must be ObjectId or StringId! It cannot be something else!`); - } - return (0, item_helpers_1.convertStringId)(referringItem); - } - } - } - else { - throw new Error(`RefferingItem is empty there is no value!`); - } -}; -exports.getReferenceItemId = getReferenceItemId; -const getReferencesItemIds = (referencedItem) => { - if (referencedItem) { - let saveObjectIds = []; - if ((0, lodash_1.isArray)(referencedItem)) { - for (const i of referencedItem) { - saveObjectIds.push((0, exports.getReferenceItemId)(i)); - } - return saveObjectIds; - } - else { - saveObjectIds.push((0, exports.getReferenceItemId)(referencedItem)); - return saveObjectIds; - } - } - else { - throw new Error(`ReferencedItem is empty there is no value!`); - } -}; -exports.getReferencesItemIds = getReferencesItemIds; diff --git a/app/lib/Helpers/secret_helpers.js b/app/lib/Helpers/secret_helpers.js deleted file mode 100644 index 2a724ab3..00000000 --- a/app/lib/Helpers/secret_helpers.js +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getHelperSecretsCache = exports.getCachedSecret = void 0; -const wix_secrets_backend_v2_1 = require("wix-secrets-backend.v2"); -const wixAuth = __importStar(require("wix-auth")); -const node_cache_1 = __importDefault(require("node-cache")); -const cache = new node_cache_1.default(); -const getSecretValue = wixAuth.elevate(wix_secrets_backend_v2_1.secrets.getSecretValue); -async function getCachedSecret(secretName, parse) { - try { - if (typeof secretName !== "string") { - throw new Error(`secretName param is not string!`); - } - let secret = cache.get(secretName); - if (secret === undefined) { - const { value } = await getSecretValue(secretName); - if (parse === true) { - let objectSecret; - try { - objectSecret = JSON.parse(value); - } - catch (err) { - throw new Error(`failed to parse JSON for secret '${secretName}': ${err}`); - } - if (typeof objectSecret === 'object' && objectSecret !== null) { - secret = objectSecret; - } - else { - throw new Error(`parsed JSON is not an object for secret '${secretName}'`); - } - } - else { - secret = value; - } - cache.set(secretName, secret, 60 * 6); - } - return secret; - } - catch (err) { - throw new Error(`Error on general cached secret helpers: ${err}`); - } -} -exports.getCachedSecret = getCachedSecret; -function getHelperSecretsCache() { - return cache; -} -exports.getHelperSecretsCache = getHelperSecretsCache; diff --git a/app/lib/Helpers/validator.js b/app/lib/Helpers/validator.js deleted file mode 100644 index 4d23a680..00000000 --- a/app/lib/Helpers/validator.js +++ /dev/null @@ -1,238 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.copyOwnPropsOnly = exports.validateParams = void 0; -const reference_helpers_1 = require("./reference_helpers"); -const item_helpers_1 = require("./item_helpers"); -const lodash_1 = require("lodash"); -async function validateParams(params, requiredParams, func) { - try { - let safeItem; - let safeOptions; - let safeReferringItemId; - let safeReferencedItemIds; - let safeItemId; - let safeValue; - let safeItems; - let safeItemIds; - let safeQueryOptions; - let safeCollectionOptions; - let safeCollectionFilter; - const paramKeys = Object.entries(params); - for (const [key, value] of paramKeys) { - switch (key) { - case "collectionId": { - if (value) { - if (typeof value !== "string") { - throw new Error(`type of collectionId is not string!`); - } - } - break; - } - case "item": { - if (value) { - if (typeof value !== "object") { - throw new Error(`type of item is not object!`); - } - else { - safeItem = copyOwnPropsOnly(value); - } - } - break; - } - case "options": { - if (value) { - if (typeof value !== "object") { - throw new Error(`type of options is not object!`); - } - else { - safeOptions = copyOwnPropsOnly(value); - } - } - break; - } - case "referringItem": { - safeReferringItemId = (0, reference_helpers_1.getReferenceItemId)(value); - break; - } - case "referencedItem": { - safeReferencedItemIds = (0, reference_helpers_1.getReferencesItemIds)(value); - break; - } - case "propertyName": { - if (value) { - if (typeof value !== "string") { - throw new Error(`propertyName must be string!`); - } - } - break; - } - case "itemId": { - if (value) { - safeItemId = (0, item_helpers_1.convertStringId)(value); - } - break; - } - case "value": { - if (value && typeof value === "object" && isPlainObject(value)) { - safeValue = copyOwnPropsOnly(value); - } - else { - safeValue = value; - } - break; - } - case 'items': { - if (value) { - if ((0, lodash_1.isArray)(value)) { - safeItems = value.map((item) => { - return copyOwnPropsOnly(item); - }); - } - else { - throw new Error(`type of items is not array!`); - } - } - break; - } - case 'itemIds': { - if (value) { - if ((0, lodash_1.isArray)(value)) { - safeItemIds = value.map((itemId) => { - return (0, item_helpers_1.convertStringId)(itemId); - }); - } - else { - throw new Error(`itemIds must be an array`); - } - } - break; - } - case 'queryOptions': { - if (value) { - if (typeof value !== "object") { - throw new Error(`type of queryOptions is not object!`); - } - else { - safeQueryOptions = copyOwnPropsOnly(value); - } - } - break; - } - case 'collectionOptions': { - if (value) { - if (typeof value !== "object") { - throw new Error(`type of collection action options is not object!`); - } - else { - safeCollectionOptions = copyOwnPropsOnly(value); - } - } - break; - } - case 'collectionFilter': { - if (value) { - if (typeof value !== "object") { - throw new Error(`type of collection filter is not object!`); - } - else { - safeCollectionFilter = copyOwnPropsOnly(value); - } - } - break; - } - case "suppressAuth": { - if (typeof value !== "boolean") { - throw new Error(`type of suppressAuth is not boolean!`); - } - break; - } - default: { - break; - } - } - if (requiredParams.includes(key)) { - if (!value || value === null || value === undefined) { - throw new Error(`${key} is required param for ${func} function!`); - } - } - } - const functionList = [ - "update", - "replace", - "bulkUpdate" - ]; - if (functionList.includes(func)) { - checkItemIds(params, func); - } - return { - safeItem, - safeOptions, - safeReferencedItemIds, - safeReferringItemId, - safeItemId, - safeValue, - safeItems, - safeItemIds, - safeQueryOptions, - safeCollectionOptions, - safeCollectionFilter - }; - } - catch (err) { - throw new Error(`Validation Error!, ${err}`); - } -} -exports.validateParams = validateParams; -function checkItemIds(params, func) { - try { - const bulkFunctions = [ - "bulkUpdate" - ]; - if (bulkFunctions.includes(func)) { - for (const item of params.items) { - if (!item._id) { - throw new Error(`item must contain _id property, _id is missing from item object in items array!`); - } - } - } - else { - if (!params.item._id) { - throw new Error(`item must contain _id property, _id is missing from item object!`); - } - } - return null; - } - catch (err) { - throw new Error(`params doesn't contain item data (weiv-data internal error please report BUG)`); - } -} -function copyOwnPropsOnly(src) { - const result = Object.create(null); - function copyObject(value) { - if (isPlainObject(value)) { - return copyOwnPropsOnly(value); - } - else { - return value; - } - } - for (const key of Object.getOwnPropertyNames(src)) { - if (key !== "__proto__" || "constructor" || "prototype") { - if (typeof src[key] === "object") { - result[key] = copyObject(src[key]); - } - else { - result[key] = src[key]; - } - } - } - return result; -} -exports.copyOwnPropsOnly = copyOwnPropsOnly; -function isPlainObject(value) { - if (typeof value !== 'object' || value === null) - return false; - if (Array.isArray(value)) - return false; - return value.constructor === Object; -} diff --git a/app/lib/Hooks/hook_manager.js b/app/lib/Hooks/hook_manager.js deleted file mode 100644 index f1389826..00000000 --- a/app/lib/Hooks/hook_manager.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.runErrorHook = exports.runDataHook = void 0; -const data_hooks = __importStar(require("../../../../../../../../../user-code/backend/WeivData/data")); -const name_helpers_1 = require("../Helpers/name_helpers"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -function hookExist(collectionId, hookName) { - if (typeof hookName !== "string") { - throw new Error("type of hook name is not string!"); - } - const { collectionName, dbName } = (0, name_helpers_1.splitCollectionId)(collectionId); - const hook = data_hooks[`${dbName.toLowerCase()}_${collectionName.toLowerCase()}_${hookName}`]; - if (hook) { - return hook; - } - else { - return undefined; - } -} -async function runDataHook(collectionId, hookName, args) { - try { - if (typeof hookName !== "string" && typeof collectionId !== "string") { - throw new Error("type of hook name or collection id is not string!"); - } - const hookFunction = hookExist(collectionId, hookName); - if (hookFunction) { - const item = await hookFunction(...args); - return item; - } - else { - return undefined; - } - } - catch (err) { - const context = (0, hook_helpers_1.prepareHookContext)(collectionId); - runErrorHook(collectionId, new Error(`${err}`), context); - throw new Error(`WeivData - Hook error: ${collectionId}, ${hookName}, err: ${err}`); - } -} -exports.runDataHook = runDataHook; -function runErrorHook(collectionId, err, context) { - console.error(err.message); - const errorHandlerFunction = hookExist(collectionId, "onFailure"); - if (errorHandlerFunction) { - errorHandlerFunction(err, context); - } -} -exports.runErrorHook = runErrorHook; diff --git a/app/lib/Query/query_data.js b/app/lib/Query/query_data.js deleted file mode 100644 index fddd4b14..00000000 --- a/app/lib/Query/query_data.js +++ /dev/null @@ -1,335 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.QueryResult = void 0; -const data_filter_1 = require("../Filter/data_filter"); -const lodash_1 = require("lodash"); -const validator_1 = require("../Helpers/validator"); -const connection_helpers_1 = require("../Helpers/connection_helpers"); -const hook_helpers_1 = require("../Helpers/hook_helpers"); -const hook_manager_1 = require("../Hooks/hook_manager"); -const item_helpers_1 = require("../Helpers/item_helpers"); -class Query extends data_filter_1.WeivDataFilter { - constructor(collectionId) { - super(); - this._sort = new Map(); - this._fields = new Array(); - this._includes = new Array(); - this._limitNumber = 50; - this._skipNumber = 0; - this._isAggregate = false; - this._collectionId = collectionId; - } - ascending(...propertyName) { - if (!propertyName || !(0, lodash_1.isArray)(propertyName)) { - throw new Error(`WeivData - propertyName is not a valid value!`); - } - this.__addSort__(1, propertyName); - return this; - } - descending(...propertyName) { - if (!propertyName || !(0, lodash_1.isArray)(propertyName)) { - throw new Error(`WeivData - propertyName is not a valid value!`); - } - this.__addSort__(-1, propertyName); - return this; - } - limit(limit) { - if (typeof limit !== "number") { - throw new Error(`WeivData - Unvalid value for limit it's either undefined or not a number!`); - } - else { - this._limitNumber = limit; - return this; - } - } - skip(skip) { - if (typeof skip !== "number") { - throw new Error(`WeivData - Unvalid value for skip it's either undefined or not a number!`); - } - else { - this._skipNumber = skip; - return this; - } - } - fields(...propertyName) { - if (!propertyName || !(0, lodash_1.isArray)(propertyName)) { - throw new Error(`WeivData - propertyName is not a valid value!`); - } - for (const name of propertyName) { - if (typeof name !== "string") { - throw new Error(`WeivData - propertyName doesn't contain value/s!`); - } - else { - this._fields.push(name); - } - } - this._isAggregate = true; - return this; - } - include(...includes) { - if (!includes || !(0, lodash_1.isArray)(includes)) { - throw new Error(`WeivData - include is not a valid value!`); - } - for (const include of includes) { - if (typeof include !== "object") { - throw new Error(`WeivData - include values must be an object ${include} is not a valid value!`); - } - else { - if (!include["collectionName"] || !include["fieldName"] || typeof include["collectionName"] !== "string" || typeof include["fieldName"] !== "string") { - throw new Error(`WeivData - each include object must contain collectionName and fieldName values as string!`); - } - const safeInclude = (0, validator_1.copyOwnPropsOnly)(include); - this._includes.push(safeInclude); - } - } - this._isAggregate = true; - return this; - } - __addSort__(sort, propertyName) { - for (const name of propertyName) { - if (typeof name !== "string") { - throw new Error(`WeivData - propertyName doesn't contain valid value/s!`); - } - else { - this._sort.set(name, sort); - } - } - } -} -class QueryResult extends Query { - async count(options) { - try { - const { suppressAuth, suppressHooks, readConcern } = (0, validator_1.copyOwnPropsOnly)(options || {}); - await this._handleConnection_(suppressAuth); - const context = (0, hook_helpers_1.prepareHookContext)(this._collectionId); - let editedQurey; - if (suppressHooks != true) { - editedQurey = await (0, hook_manager_1.runDataHook)(this._collectionId, "beforeCount", [this, context]).catch((err) => { - throw new Error(`beforeCount Hook Failure ${err}`); - }); - } - const totalCount = await this._collection.countDocuments(!editedQurey ? this._filters.$match : editedQurey._filters.$match, { readConcern }); - if (suppressHooks != true) { - let editedCount = await (0, hook_manager_1.runDataHook)(this._collectionId, "afterCount", [totalCount, context]).catch((err) => { - throw new Error(`afterCount Hook Failure ${err}`); - }); - if (editedCount) { - return editedCount; - } - } - return totalCount; - } - catch (err) { - throw new Error(`WeivData - Error when using count with weivData.query: ${err}`); - } - } - async distnict(propertyName, options) { - try { - if (!propertyName || typeof propertyName !== "string") { - throw new Error(`WeivData - propertyName is not string or not a valid value!`); - } - options = (0, validator_1.copyOwnPropsOnly)(options || {}); - const { suppressAuth, readConcern } = options; - await this._handleConnection_(suppressAuth); - const pipeline = []; - pipeline.push(this._filters); - pipeline.push({ $group: { _id: `$${propertyName}` } }); - pipeline.push({ $project: { distnict: "$_id", _id: 0 } }); - const aggregationCursor = this._collection.aggregate(pipeline, { readConcern }); - const items = (await aggregationCursor.toArray()).map(i => i.distinct); - const hasNext = await aggregationCursor.hasNext(); - const totalCount = await this.__getTotalCount__(options?.omitTotalCount || false); - return { - items: items.map((item) => { - if (item._id) { - item._id = (0, item_helpers_1.convertObjectId)(item._id); - } - return item; - }), - length: items.length, - currentPage: this._currentPage, - pageSize: this._limitNumber, - totalCount, - totalPages: Math.ceil(totalCount / this._limitNumber), - hasNext: () => hasNext, - hasPrev: () => this.__hasPrev__(), - next: async () => { - this._currentPage++; - return this.distnict(propertyName, options); - }, - prev: async () => { - this._currentPage--; - return this.distnict(propertyName, options); - }, - _filters: this._filters, - _pipeline: pipeline - }; - } - catch (err) { - throw new Error(`WeivData - Error when using distnict with weivData.query: ${err}`); - } - } - async find(options) { - try { - options = (0, validator_1.copyOwnPropsOnly)(options || {}); - const { suppressAuth, suppressHooks, readConcern, omitTotalCount } = options; - await this._handleConnection_(suppressAuth); - const context = (0, hook_helpers_1.prepareHookContext)(this._collectionId); - if (suppressHooks != true) { - await (0, hook_manager_1.runDataHook)(this._collectionId, "beforeQuery", [this, context]).catch((err) => { - throw new Error(`beforeQuery Hook Failure ${err}`); - }); - } - let totalCount; - let items; - let hasNext; - if (this._isAggregate) { - const pipeline = this.__createAggregationPipeline__(); - const aggregationCursor = this._collection.aggregate(pipeline, { readConcern }); - items = await aggregationCursor.toArray(); - hasNext = await aggregationCursor.hasNext(); - totalCount = await this.__getTotalCount__(omitTotalCount || false); - } - else { - const findCursor = this._collection.find(this._filters.$match, { readConcern }); - for (const [key, value] of this._sort.entries()) { - findCursor.sort(key, value); - } - findCursor.limit(this._limitNumber); - findCursor.skip(this._skipNumber || 0 + ((this._currentPage - 1) * this._limitNumber)); - items = await findCursor.toArray(); - hasNext = await findCursor.hasNext(); - totalCount = await this.__getTotalCount__(omitTotalCount || false); - } - if (suppressHooks != true) { - const hookedItems = items.map(async (item, index) => { - const editedItem = await (0, hook_manager_1.runDataHook)(this._collectionId, "afterQuery", [item, context]).catch((err) => { - throw new Error(`afterQuery Hook Failure ${err} Item Index: ${index}`); - }); - if (editedItem) { - return editedItem; - } - else { - return item; - } - }); - items = await Promise.all(hookedItems); - } - return { - items: items.map((item) => { - if (item._id) { - item._id = (0, item_helpers_1.convertObjectId)(item._id); - } - return item; - }), - length: items.length, - currentPage: this._currentPage, - pageSize: this._limitNumber, - totalCount, - totalPages: Math.ceil(totalCount / this._limitNumber), - hasNext: () => hasNext, - hasPrev: () => this.__hasPrev__(), - next: async () => { - this._currentPage++; - return this.find(options); - }, - prev: async () => { - this._currentPage--; - return this.find(options); - }, - _filters: this._filters, - _pipeline: this._isAggregate ? this.__createAggregationPipeline__() : undefined - }; - } - catch (err) { - console.error('WeivData - Error pipeline: ', this.__createAggregationPipeline__()); - console.error('WeivData - Error query: ', this._filters); - throw new Error(`WeivData - Error when using find with weivData.query, details: ${err}`); - } - } - constructor(collectionId) { - if (!collectionId || typeof collectionId !== "string") { - throw new Error(`WeivData - CollectionID must be string and shouldn't be undefined or null!`); - } - super(collectionId); - this._currentPage = 1; - } - async _handleConnection_(suppressAuth) { - if (!this._collection || !this._database) { - const { collection, database } = await (0, connection_helpers_1.connectionHandler)(this._collectionId, suppressAuth); - this._database = database; - this._collection = collection; - } - } - __createAggregationPipeline__() { - const pipeline = []; - if (!(0, lodash_1.isEmpty)(this._filters.$match)) { - pipeline.push(this._filters); - } - for (const include of this._includes) { - const lookUpObj = { - $lookup: { - from: include.collectionName, - localField: include.fieldName, - foreignField: !include.foreignField ? "_id" : include.foreignField, - as: !include.as ? include.fieldName : include.as, - pipeline: [ - { $limit: include.maxItems || 50 }, - { $sort: this.__getSortFromInclude__(include) } - ] - } - }; - if (include.countItems) { - pipeline.push({ - $addFields: { - [`${include.fieldName}Length`]: { - $cond: { - if: { $isArray: `$${include.fieldName}` }, - then: { $size: `$${include.fieldName}` }, - else: 0 - } - } - } - }); - } - pipeline.push(lookUpObj); - } - for (const [key, value] of this._sort.entries()) { - pipeline.push({ - $sort: { - [key]: value - } - }); - } - let fields = {}; - for (const field of this._fields) { - (0, lodash_1.merge)(fields, { [field]: 1 }); - } - if (!(0, lodash_1.isEmpty)(fields)) { - pipeline.push({ $project: fields }); - } - pipeline.push({ $skip: this._skipNumber || 0 + ((this._currentPage - 1) * this._limitNumber) }); - pipeline.push({ $limit: this._limitNumber || 50 }); - return pipeline; - } - __getSortFromInclude__(includeObj) { - if (includeObj.sort) { - return (0, validator_1.copyOwnPropsOnly)(includeObj.sort); - } - else { - return { _createdDate: 1 }; - } - } - __hasPrev__() { - return this._currentPage > 1; - } - async __getTotalCount__(omitTotalCount) { - if (omitTotalCount) { - return await this._collection.estimatedDocumentCount(); - } - else { - return await this._collection.countDocuments(); - } - } -} -exports.QueryResult = QueryResult; diff --git a/app/lib/index.js b/app/lib/index.js deleted file mode 100644 index 302122a4..00000000 --- a/app/lib/index.js +++ /dev/null @@ -1,117 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports._version = exports.listCollections = exports.renameCollection = exports.deleteCollection = exports.createCollection = exports.pull = exports.push = exports.increment = exports.multiply = exports.getAndUpdate = exports.getAndReplace = exports.getAndRemove = exports.findOne = exports.replace = exports.native = exports.flushCache = exports.convertId = exports.update = exports.truncate = exports.save = exports.replaceReferences = exports.removeReference = exports.remove = exports.isReferenced = exports.insertReference = exports.insert = exports.get = exports.bulkUpdate = exports.bulkSave = exports.bulkRemove = exports.bulkInsert = exports.queryReferenced = exports.aggregate = exports.filter = exports.query = void 0; -const aggregate_data_1 = require("./Aggregate/aggregate_data"); -const data_filter_1 = require("./Filter/data_filter"); -const query_data_1 = require("./Query/query_data"); -const queryReferenced_1 = require("./Functions/QueryReferenced/queryReferenced"); -Object.defineProperty(exports, "queryReferenced", { enumerable: true, get: function () { return queryReferenced_1.queryReferenced; } }); -const bulkInsert_1 = require("./Functions/bulkInsert"); -Object.defineProperty(exports, "bulkInsert", { enumerable: true, get: function () { return bulkInsert_1.bulkInsert; } }); -const bulkRemove_1 = require("./Functions/bulkRemove"); -Object.defineProperty(exports, "bulkRemove", { enumerable: true, get: function () { return bulkRemove_1.bulkRemove; } }); -const bulkSave_1 = require("./Functions/bulkSave"); -Object.defineProperty(exports, "bulkSave", { enumerable: true, get: function () { return bulkSave_1.bulkSave; } }); -const bulkUpdate_1 = require("./Functions/bulkUpdate"); -Object.defineProperty(exports, "bulkUpdate", { enumerable: true, get: function () { return bulkUpdate_1.bulkUpdate; } }); -const get_1 = require("./Functions/get"); -Object.defineProperty(exports, "get", { enumerable: true, get: function () { return get_1.get; } }); -const insert_1 = require("./Functions/insert"); -Object.defineProperty(exports, "insert", { enumerable: true, get: function () { return insert_1.insert; } }); -const insertReference_1 = require("./Functions/insertReference"); -Object.defineProperty(exports, "insertReference", { enumerable: true, get: function () { return insertReference_1.insertReference; } }); -const isReferenced_1 = require("./Functions/isReferenced"); -Object.defineProperty(exports, "isReferenced", { enumerable: true, get: function () { return isReferenced_1.isReferenced; } }); -const remove_1 = require("./Functions/remove"); -Object.defineProperty(exports, "remove", { enumerable: true, get: function () { return remove_1.remove; } }); -const removeReference_1 = require("./Functions/removeReference"); -Object.defineProperty(exports, "removeReference", { enumerable: true, get: function () { return removeReference_1.removeReference; } }); -const replaceReferences_1 = require("./Functions/replaceReferences"); -Object.defineProperty(exports, "replaceReferences", { enumerable: true, get: function () { return replaceReferences_1.replaceReferences; } }); -const save_1 = require("./Functions/save"); -Object.defineProperty(exports, "save", { enumerable: true, get: function () { return save_1.save; } }); -const truncate_1 = require("./Functions/truncate"); -Object.defineProperty(exports, "truncate", { enumerable: true, get: function () { return truncate_1.truncate; } }); -const update_1 = require("./Functions/update"); -Object.defineProperty(exports, "update", { enumerable: true, get: function () { return update_1.update; } }); -const convertId_1 = require("./Functions/convertId"); -Object.defineProperty(exports, "convertId", { enumerable: true, get: function () { return convertId_1.convertId; } }); -const flushCache_1 = require("./Functions/flushCache"); -Object.defineProperty(exports, "flushCache", { enumerable: true, get: function () { return flushCache_1.flushCache; } }); -const native_1 = require("./Functions/native"); -Object.defineProperty(exports, "native", { enumerable: true, get: function () { return native_1.native; } }); -const replace_1 = require("./Functions/replace"); -Object.defineProperty(exports, "replace", { enumerable: true, get: function () { return replace_1.replace; } }); -const findOne_1 = require("./Functions/Helpers/findOne"); -Object.defineProperty(exports, "findOne", { enumerable: true, get: function () { return findOne_1.findOne; } }); -const getAndRemove_1 = require("./Functions/Helpers/getAndRemove"); -Object.defineProperty(exports, "getAndRemove", { enumerable: true, get: function () { return getAndRemove_1.getAndRemove; } }); -const getAndReplace_1 = require("./Functions/Helpers/getAndReplace"); -Object.defineProperty(exports, "getAndReplace", { enumerable: true, get: function () { return getAndReplace_1.getAndReplace; } }); -const getAndUpdate_1 = require("./Functions/Helpers/getAndUpdate"); -Object.defineProperty(exports, "getAndUpdate", { enumerable: true, get: function () { return getAndUpdate_1.getAndUpdate; } }); -const multiply_1 = require("./Functions/multiply"); -Object.defineProperty(exports, "multiply", { enumerable: true, get: function () { return multiply_1.multiply; } }); -const increment_1 = require("./Functions/increment"); -Object.defineProperty(exports, "increment", { enumerable: true, get: function () { return increment_1.increment; } }); -const push_1 = require("./Functions/push"); -Object.defineProperty(exports, "push", { enumerable: true, get: function () { return push_1.push; } }); -const pull_1 = require("./Functions/pull"); -Object.defineProperty(exports, "pull", { enumerable: true, get: function () { return pull_1.pull; } }); -const createCollection_1 = require("./Collections/createCollection"); -Object.defineProperty(exports, "createCollection", { enumerable: true, get: function () { return createCollection_1.createCollection; } }); -const deleteCollection_1 = require("./Collections/deleteCollection"); -Object.defineProperty(exports, "deleteCollection", { enumerable: true, get: function () { return deleteCollection_1.deleteCollection; } }); -const renameCollection_1 = require("./Collections/renameCollection"); -Object.defineProperty(exports, "renameCollection", { enumerable: true, get: function () { return renameCollection_1.renameCollection; } }); -const listCollections_1 = require("./Collections/listCollections"); -Object.defineProperty(exports, "listCollections", { enumerable: true, get: function () { return listCollections_1.listCollections; } }); -const package_json_1 = __importDefault(require("../package.json")); -const aggregate = (collectionId) => new aggregate_data_1.AggregateResult(collectionId); -exports.aggregate = aggregate; -const query = (collectionId) => new query_data_1.QueryResult(collectionId); -exports.query = query; -const filter = () => new data_filter_1.WeivDataFilter(); -exports.filter = filter; -const _version = () => package_json_1.default.version; -exports._version = _version; -exports.default = { - query, - filter, - aggregate, - queryReferenced: queryReferenced_1.queryReferenced, - bulkInsert: bulkInsert_1.bulkInsert, - bulkRemove: bulkRemove_1.bulkRemove, - bulkSave: bulkSave_1.bulkSave, - bulkUpdate: bulkUpdate_1.bulkUpdate, - get: get_1.get, - insert: insert_1.insert, - insertReference: insertReference_1.insertReference, - isReferenced: isReferenced_1.isReferenced, - remove: remove_1.remove, - removeReference: removeReference_1.removeReference, - replaceReferences: replaceReferences_1.replaceReferences, - save: save_1.save, - truncate: truncate_1.truncate, - update: update_1.update, - convertId: convertId_1.convertId, - flushCache: flushCache_1.flushCache, - native: native_1.native, - replace: replace_1.replace, - findOne: findOne_1.findOne, - getAndRemove: getAndRemove_1.getAndRemove, - getAndReplace: getAndReplace_1.getAndReplace, - getAndUpdate: getAndUpdate_1.getAndUpdate, - multiply: multiply_1.multiply, - increment: increment_1.increment, - push: push_1.push, - pull: pull_1.pull, - createCollection: createCollection_1.createCollection, - deleteCollection: deleteCollection_1.deleteCollection, - renameCollection: renameCollection_1.renameCollection, - listCollections: listCollections_1.listCollections, - _version -};