@cocreate/mongodb
Advanced tools
Comparing version
@@ -0,1 +1,8 @@ | ||
# [1.2.0](https://github.com/CoCreate-app/CoCreate-mongodb/compare/v1.1.25...v1.2.0) (2023-03-19) | ||
### Features | ||
* dynamically connect to user defined dbUrl ([343ab8e](https://github.com/CoCreate-app/CoCreate-mongodb/commit/343ab8e5a72683a3be74c24acfc4489198564c10)) | ||
## [1.1.25](https://github.com/CoCreate-app/CoCreate-mongodb/compare/v1.1.24...v1.1.25) (2023-02-01) | ||
@@ -2,0 +9,0 @@ |
{ | ||
"name": "@cocreate/mongodb", | ||
"version": "1.1.25", | ||
"version": "1.2.0", | ||
"description": "A simple mongodb component in vanilla javascript. Easily configured using HTML5 data-attributes and/or JavaScript API.", | ||
@@ -5,0 +5,0 @@ "keywords": [ |
369
src/index.js
@@ -1,5 +0,6 @@ | ||
const {MongoClient, ObjectId} = require('mongodb'); | ||
const {dotNotationToObject, queryData, searchData, sortData} = require('@cocreate/utils') | ||
const { MongoClient, ObjectId } = require('mongodb'); | ||
const { dotNotationToObject, queryData, searchData, sortData } = require('@cocreate/utils') | ||
const clients = new Map() | ||
function mongoClient(dbUrl) { | ||
async function mongoClient(dbUrl) { | ||
try { | ||
@@ -9,4 +10,4 @@ dbUrl = dbUrl || process.env.MONGO_URL; | ||
console.log('CoCreate.config.js missing dbUrl') | ||
dbClient = MongoClient.connect(dbUrl, { useNewUrlParser: true, useUnifiedTopology: true }); | ||
return dbClient; | ||
const Client = MongoClient.connect(dbUrl, { useNewUrlParser: true, useUnifiedTopology: true }); | ||
return Client; | ||
} catch (error) { | ||
@@ -20,9 +21,24 @@ console.error(error) | ||
let dbClient; | ||
let platformClient; | ||
mongoClient().then(Client => { | ||
dbClient = Client | ||
platformClient = Client | ||
}); | ||
async function dbClient(data) { | ||
// ToDo: provide platform client only to specific collections ['permissions', 'metrics', 'organizations', 'users'] | ||
if (!data.dbs) | ||
return platformClient | ||
let client = clients.get(data.dbs) | ||
if (!client) { | ||
client = await mongoClient(data.dbs) | ||
clients.set(data.dbs, client) | ||
} | ||
return client | ||
} | ||
async function databaseStats(data) { | ||
let stats = await dbClient.db(data.organization_id).stats() | ||
const client = await dbClient(data) | ||
if (!client) return | ||
let db = client.db(data.organization_id) | ||
let stats = db.stats() | ||
return stats | ||
@@ -47,26 +63,27 @@ } | ||
function database(action, data){ | ||
return new Promise((resolve, reject) => { | ||
function database(action, data) { | ||
return new Promise(async (resolve, reject) => { | ||
let type = 'database' | ||
let databaseArray = [] | ||
try { | ||
const client = await dbClient(data) | ||
if (!client) return | ||
if (action == 'readDatabase') { | ||
let db = dbClient.db().admin(); | ||
const db = client.db().admin(); | ||
// List all the available databases | ||
db.listDatabases(function(err, dbs) { | ||
for (let database of dbs.databases){ | ||
db.listDatabases(function (err, dbs) { | ||
for (let database of dbs.databases) { | ||
let isFilter = queryData(database, data.filter.query) | ||
if (isFilter) | ||
databaseArray.push({database, db: 'mongodb'}) | ||
databaseArray.push({ database, db: 'mongodb' }) | ||
} | ||
resolve(createData(data, databaseArray, type)) | ||
resolve(createData(data, databaseArray, type)) | ||
}) | ||
} | ||
if (action == 'deleteDatabase') { | ||
const db = dbClient.db(data.database); | ||
const db = client.db(data.database); | ||
db.dropDatabase().then(response => { | ||
@@ -76,3 +93,3 @@ resolve(response) | ||
} | ||
} catch(error) { | ||
} catch (error) { | ||
errorHandler(data, error) | ||
@@ -89,3 +106,3 @@ console.log(action, 'error', error); | ||
function createCollection(data){ | ||
function createCollection(data) { | ||
return collection('createCollection', data) | ||
@@ -106,12 +123,15 @@ } | ||
function collection(action, data){ | ||
return new Promise((resolve, reject) => { | ||
function collection(action, data) { | ||
return new Promise(async (resolve, reject) => { | ||
let type = 'collection' | ||
let collectionArray = []; | ||
try { | ||
const client = await dbClient(data) | ||
if (!client) return | ||
if (data.request) | ||
data.collection = data.request | ||
let databases = data.database; | ||
let databases = data.database; | ||
if (!Array.isArray(databases)) | ||
@@ -122,11 +142,12 @@ databases = [databases] | ||
for (let database of databases) { | ||
const db = dbClient.db(database); | ||
const db = client.db(database); | ||
if (action == 'readCollection') { | ||
let {query, sort} = getFilters(data); | ||
let { query, sort } = getFilters(data); | ||
db.listCollections().toArray(function(error, result) { | ||
db.listCollections().toArray(function (error, result) { | ||
if (error) | ||
errorHandler(data, error, database) | ||
if (result) { | ||
@@ -136,3 +157,3 @@ for (let res of result) { | ||
if (isFilter) | ||
collectionArray.push({name: res.name, database, db: 'mongodb'}) | ||
collectionArray.push({ name: res.name, database, db: 'mongodb' }) | ||
} | ||
@@ -144,5 +165,5 @@ } | ||
data = createData(data, collectionArray, type) | ||
resolve(data) | ||
resolve(data) | ||
} | ||
}) | ||
}) | ||
} else { | ||
@@ -154,4 +175,4 @@ let collections | ||
else | ||
collections = data.collection; | ||
collections = data.collection; | ||
if (!Array.isArray(collections)) | ||
@@ -162,5 +183,5 @@ collections = [collections] | ||
for (let collection of collections) { | ||
if (action == 'createCollection') { | ||
db.createCollection(collection, function(error, result) { | ||
db.createCollection(collection, function (error, result) { | ||
if (error) | ||
@@ -170,11 +191,11 @@ errorHandler(data, error, database, collection) | ||
if (result) | ||
collectionArray.push({name: collection, database, db: 'mongodb'}) | ||
collectionArray.push({ name: collection, database, db: 'mongodb' }) | ||
collectionsLength -= 1 | ||
collectionsLength -= 1 | ||
if (!collectionsLength) | ||
databasesLength -= 1 | ||
if (!databasesLength && !collectionsLength) { | ||
data = createData(data, collectionArray, type) | ||
resolve(data) | ||
resolve(data) | ||
} | ||
@@ -186,17 +207,17 @@ }) | ||
} | ||
const collectionObj = db.collection(collection); | ||
if (action == 'updateCollection') { | ||
collectionObj.rename(value, function(error, result) { | ||
collectionObj.rename(value, function (error, result) { | ||
if (error) | ||
errorHandler(data, error, database, collection) | ||
if (result) | ||
collectionArray.push({name: value, oldName: collection, database, db: 'mongodb'}) | ||
collectionsLength -= 1 | ||
collectionArray.push({ name: value, oldName: collection, database, db: 'mongodb' }) | ||
collectionsLength -= 1 | ||
if (!collectionsLength) | ||
databasesLength -= 1 | ||
if (!databasesLength && !collectionsLength) { | ||
@@ -211,13 +232,13 @@ data = createData(data, collectionArray, type) | ||
if (action == 'deleteCollection') { | ||
collectionObj.drop( function(error, result) { | ||
collectionObj.drop(function (error, result) { | ||
if (error) | ||
errorHandler(data, error, database, collection) | ||
if (result) | ||
collectionArray.push({name: collection, database, db: 'mongodb'}) | ||
collectionsLength -= 1 | ||
collectionArray.push({ name: collection, database, db: 'mongodb' }) | ||
collectionsLength -= 1 | ||
if (!collectionsLength) | ||
databasesLength -= 1 | ||
if (!databasesLength && !collectionsLength) { | ||
@@ -229,3 +250,3 @@ data = createData(data, collectionArray, type) | ||
}) | ||
} | ||
@@ -237,3 +258,4 @@ } | ||
} | ||
} catch(error) { | ||
} catch (error) { | ||
errorHandler(data, error) | ||
@@ -249,3 +271,3 @@ console.log(action, 'error', error); | ||
function createDocument(data){ | ||
function createDocument(data) { | ||
return document('createDocument', data) | ||
@@ -266,5 +288,8 @@ } | ||
function document(action, data){ | ||
function document(action, data) { | ||
return new Promise(async (resolve, reject) => { | ||
try { | ||
const client = await dbClient(data) | ||
if (!client) return | ||
let type = 'document' | ||
@@ -279,9 +304,9 @@ let documents = []; | ||
data['timeStamp'] = new Date().toISOString() | ||
let isFilter | ||
if (data.filter && data.filter.query) | ||
isFilter = true | ||
let databases = data.database; | ||
let databases = data.database; | ||
if (!Array.isArray(databases)) | ||
@@ -298,6 +323,6 @@ databases = [databases] | ||
for (let collection of collections) { | ||
const db = dbClient.db(database); | ||
const db = client.db(database); | ||
const collectionObj = db.collection(collection); | ||
let {query, sort} = getFilters(data); | ||
let { query, sort } = getFilters(data); | ||
if (data['organization_id']) { | ||
@@ -324,5 +349,5 @@ query['organization_id'] = { $eq: data['organization_id'] } | ||
data[type][i]._id = ObjectId() | ||
else | ||
else | ||
data[type][i]._id = ObjectId(data[type][i]._id) | ||
data[type][i]['created'] = {on: data.timeStamp, by: data.user_id || data.clientId} | ||
data[type][i]['created'] = { on: data.timeStamp, by: data.user_id || data.clientId } | ||
} | ||
@@ -332,16 +357,16 @@ if (action == 'readDocument' && data[type][i]._id) { | ||
} | ||
if (action =='updateDocument') { | ||
if (action == 'updateDocument') { | ||
if (data[type][i]._id) | ||
update_ids.push({_id: data[type][i]._id, updateDoc: data[type][i], updateType: '_id'}) | ||
update_ids.push({ _id: data[type][i]._id, updateDoc: data[type][i], updateType: '_id' }) | ||
if (!data[type][i]._id) | ||
updateData = createUpdate({document: [data[type][i]]}, type) | ||
updateData = createUpdate({ document: [data[type][i]] }, type) | ||
data[type][i]['modified'] = {on: data.timeStamp, by: data.user_id || data.clientId} | ||
data[type][i]['modified'] = { on: data.timeStamp, by: data.user_id || data.clientId } | ||
} | ||
if (action =='deleteDocument') { | ||
if (action == 'deleteDocument') { | ||
if (data[type][i]._id) { | ||
_ids.push(ObjectId(data[type][i]._id)) | ||
documents.push({_id: data[type][i]._id, db: 'mongodb', database, collection}) | ||
documents.push({ _id: data[type][i]._id, db: 'mongodb', database, collection }) | ||
} | ||
@@ -353,23 +378,23 @@ } | ||
else if (_ids.length > 0) | ||
query['_id'] = {$in: _ids} | ||
query['_id'] = { $in: _ids } | ||
} | ||
if (action == 'createDocument') { | ||
collectionObj.insertMany(data[type], function(error, result) { | ||
collectionObj.insertMany(data[type], function (error, result) { | ||
if (error) | ||
errorHandler(data, error, database, collection) | ||
for (let i = 0; i < data[type].length; i++) | ||
documents.push({db: 'mongodb', database, collection, ...data[type][i]}) | ||
documents.push({ db: 'mongodb', database, collection, ...data[type][i] }) | ||
collectionsLength -= 1 | ||
collectionsLength -= 1 | ||
if (!collectionsLength) | ||
databasesLength -= 1 | ||
if (!databasesLength && !collectionsLength) { | ||
data = createData(data, documents, type) | ||
resolve(data) | ||
resolve(data) | ||
} | ||
}); | ||
}); | ||
} | ||
@@ -382,3 +407,3 @@ | ||
data.filter.count = count | ||
if (data.filter.startIndex) | ||
@@ -391,7 +416,7 @@ index = data.filter.startIndex | ||
} | ||
collectionObj.find(query).limit(limit).sort(sort).toArray(function(error, result) { | ||
collectionObj.find(query).limit(limit).sort(sort).toArray(function (error, result) { | ||
if (error) | ||
errorHandler(data, error, database, collection) | ||
if (result) { | ||
@@ -417,4 +442,4 @@ // ToDo: forEach at cursor | ||
if (data.returnDocument == false) { | ||
for (let item of data['data']) { | ||
for (let item of data['data']) { | ||
let resp = {}; | ||
@@ -425,3 +450,3 @@ resp['_id'] = tmp['_id'] | ||
} | ||
data['data'] = documents | ||
@@ -431,9 +456,9 @@ } | ||
collectionsLength -= 1 | ||
collectionsLength -= 1 | ||
if (!collectionsLength) | ||
databasesLength -= 1 | ||
if (!databasesLength && !collectionsLength) { | ||
data = createData(data, documents, type) | ||
resolve(data) | ||
resolve(data) | ||
} | ||
@@ -445,8 +470,8 @@ }); | ||
const queryDocs = () => { | ||
return new Promise((resolve, reject) => { | ||
collectionObj.find(query).sort(sort).toArray(function(error, result) { | ||
return new Promise(async (resolve, reject) => { | ||
collectionObj.find(query).sort(sort).toArray(function (error, result) { | ||
if (error) | ||
errorHandler(data, error, database, collection) | ||
if (data.filter && data.filter.search) { | ||
@@ -468,3 +493,3 @@ let searchResult = [] | ||
} | ||
let Result, $update, update, projection; | ||
@@ -479,9 +504,9 @@ | ||
if (action == 'deleteDocument') | ||
documents.push({_id: doc._id, db: 'mongodb', database, collection}) | ||
documents.push({ _id: doc._id, db: 'mongodb', database, collection }) | ||
else | ||
doc['modified'] = {on: data.timeStamp, by: data.user_id || data.clientId} | ||
doc['modified'] = { on: data.timeStamp, by: data.user_id || data.clientId } | ||
_ids.push(doc._id) | ||
} | ||
update_ids.push({updateType: 'filter'}) | ||
update_ids.push({ updateType: 'filter' }) | ||
} | ||
@@ -491,15 +516,15 @@ | ||
let docsLength = update_ids.length | ||
for (let {updateDoc, updateType} of update_ids) { | ||
for (let { updateDoc, updateType } of update_ids) { | ||
if (updateType == '_id') { | ||
let update_id = updateDoc._id | ||
query['_id'] = ObjectId(update_id) | ||
$update = createUpdate({document: [updateDoc]}, type) | ||
$update = createUpdate({ document: [updateDoc] }, type) | ||
update = $update.update | ||
projection = $update.projection | ||
documents.push({_id: update_id, db: 'mongodb', database, collection, ...update['$set']}) | ||
documents.push({ _id: update_id, db: 'mongodb', database, collection, ...update['$set'] }) | ||
} | ||
if (updateType == 'filter') { | ||
query['_id'] = {$in: _ids} | ||
query['_id'] = { $in: _ids } | ||
$update = updateData | ||
@@ -509,3 +534,3 @@ update = $update.update | ||
for (let _id of _ids) | ||
documents.push({_id, db: 'mongodb', database, collection, ...update['$set']}) | ||
documents.push({ _id, db: 'mongodb', database, collection, ...update['$set'] }) | ||
@@ -515,7 +540,7 @@ } | ||
update['$set']['organization_id'] = data.organization_id | ||
collectionObj.updateMany(query, update, { | ||
upsert: data.upsert, | ||
projection | ||
}).then((result) => { | ||
}).then((result) => { | ||
@@ -528,25 +553,25 @@ }).catch((error) => { | ||
if (!docsLength) | ||
collectionsLength -= 1 | ||
collectionsLength -= 1 | ||
if (!collectionsLength) | ||
databasesLength -= 1 | ||
if (!databasesLength && !collectionsLength) { | ||
data = createData(data, documents, type) | ||
resolve(data) | ||
resolve(data) | ||
} | ||
}) | ||
} | ||
} | ||
if (!update_ids.length) { | ||
docsLength -= 1 | ||
if (!docsLength) | ||
collectionsLength -= 1 | ||
collectionsLength -= 1 | ||
if (!collectionsLength) | ||
databasesLength -= 1 | ||
if (!databasesLength && !collectionsLength) { | ||
data = createData(data, documents, type) | ||
resolve(data) | ||
resolve(data) | ||
} | ||
@@ -561,13 +586,13 @@ } | ||
else if (_ids.length > 0) | ||
query['_id'] = {$in: _ids} | ||
collectionObj.deleteMany(query, function(error, result) { | ||
collectionsLength -= 1 | ||
query['_id'] = { $in: _ids } | ||
collectionObj.deleteMany(query, function (error, result) { | ||
collectionsLength -= 1 | ||
if (!collectionsLength) | ||
databasesLength -= 1 | ||
if (!databasesLength && !collectionsLength) { | ||
data = createData(data, documents, type) | ||
resolve(data) | ||
resolve(data) | ||
} | ||
}) | ||
@@ -577,7 +602,7 @@ } | ||
} | ||
} | ||
} | ||
} catch(error) { | ||
} catch (error) { | ||
errorHandler(data, error) | ||
@@ -595,3 +620,3 @@ console.log(action, 'error', error); | ||
let update = {}, projection = {}; | ||
if (data[type][0]) { | ||
if (data[type][0]) { | ||
update['$set'] = data[type][0] | ||
@@ -605,8 +630,8 @@ // update['$set']['organization_id'] = data['organization_id']; | ||
} | ||
if ( data['deleteName'] ) { | ||
if (data['deleteName']) { | ||
update['$unset'] = replaceArray(data['deleteName']); | ||
} | ||
if ( data['updateName'] ) { | ||
if (data['updateName']) { | ||
update['$rename'] = replaceArray(data['updateName']) | ||
@@ -617,3 +642,3 @@ for (const [key, value] of Object.entries(update['$rename'])) { | ||
} else { | ||
let newValue = replaceArray({[value]: value}) | ||
let newValue = replaceArray({ [value]: value }) | ||
let oldkey = key; | ||
@@ -627,3 +652,3 @@ for (const [key] of Object.entries(newValue)) { | ||
return {update, projection} | ||
return { update, projection } | ||
@@ -640,4 +665,4 @@ } | ||
data[type] = array | ||
if (data.returnLog){ | ||
if (data.returnLog) { | ||
if (!data.log) | ||
@@ -647,3 +672,3 @@ data.log = [] | ||
} | ||
return data | ||
@@ -672,10 +697,10 @@ } | ||
if (direction == 'desc' || direction == -1) | ||
direction = -1; | ||
direction = -1; | ||
else | ||
direction = 1; | ||
sort[filter.sort[i].name] = filter.sort[i].direction | ||
} | ||
} | ||
return {query, sort} | ||
return { query, sort } | ||
} | ||
@@ -692,5 +717,5 @@ | ||
continue | ||
if (item.name == "_id") { | ||
if (item.value) | ||
if (item.value) | ||
item.value = ObjectId(item.value) | ||
@@ -705,3 +730,3 @@ else | ||
} | ||
switch (item.operator) { | ||
@@ -712,13 +737,13 @@ case '$includes': | ||
break; | ||
case '$range': | ||
if (item.value[0] !== null && item.value[1] !== null) { | ||
query[key] = {$gte: item.value[0], $lte: item.value[1]}; | ||
query[key] = { $gte: item.value[0], $lte: item.value[1] }; | ||
} else if (item.value[0] !== null) { | ||
query[key] = {$gte: item.value[0]}; | ||
query[key] = { $gte: item.value[0] }; | ||
} else if (item.value[1] !== null) { | ||
query[key] = {$lte: item.value[1]}; | ||
query[key] = { $lte: item.value[1] }; | ||
} | ||
break; | ||
case 'equals': | ||
@@ -740,4 +765,4 @@ query[$eq][item.operator] = item.value; | ||
// }); | ||
query[key] = {$in : item.value } | ||
query[key] = { $in: item.value } | ||
break; | ||
@@ -753,9 +778,9 @@ case '$nin': | ||
[item.type]: value | ||
} | ||
} | ||
} | ||
} catch(e) { | ||
} catch (e) { | ||
console.log('geowithin error'); | ||
} | ||
break; | ||
} | ||
} | ||
} | ||
@@ -772,7 +797,7 @@ | ||
function errorHandler(data, error, database, collection){ | ||
function errorHandler(data, error, database, collection) { | ||
if (typeof error == 'object') | ||
error['db'] = 'mongodb' | ||
else | ||
error = {db: 'mongodb', message: error} | ||
error = { db: 'mongodb', message: error } | ||
@@ -788,7 +813,7 @@ if (database) | ||
} | ||
function replaceArray(data) { | ||
let keys = Object.keys(data); | ||
let objectData = {}; | ||
keys.forEach((k) => { | ||
@@ -799,9 +824,9 @@ let nk = k | ||
if (nk.endsWith(']')) | ||
nk = nk.slice(0, -1) | ||
nk = nk.slice(0, -1) | ||
nk = nk.replace(/\]./g, '.'); | ||
nk = nk.replace(/\]/g, '.'); | ||
} | ||
objectData[nk] = data[k]; | ||
objectData[nk] = data[k]; | ||
}); | ||
return objectData; | ||
@@ -813,16 +838,16 @@ } | ||
databaseStats, | ||
createDatabase, | ||
readDatabase, | ||
updateDatabase, | ||
deleteDatabase, | ||
createCollection, | ||
readCollection, | ||
updateCollection, | ||
deleteCollection, | ||
createDatabase, | ||
readDatabase, | ||
updateDatabase, | ||
deleteDatabase, | ||
createDocument, | ||
readDocument, | ||
updateDocument, | ||
deleteDocument, | ||
createCollection, | ||
readCollection, | ||
updateCollection, | ||
deleteCollection, | ||
createDocument, | ||
readDocument, | ||
updateDocument, | ||
deleteDocument, | ||
} |
52515
1.03%774
2.79%