import { MongoClient } from 'mongodb'; let mongo; let db; let functionCollection = {}; export function init(connectionString) { try { mongo = new MongoClient(connectionString); db = mongo.db(); return mongo.connect().then(() => Promise.resolve(functionCollection)); } catch (e) { return Promise.reject(e); } } functionCollection.subscribe = function subscribe (collectionName, filter) { let collection = db.collection(collectionName); return collection .find(filter, {}) .toArray(); } functionCollection.persist = function persist (collectionName, filter, fieldName, value) { let collection = db.collection(collectionName); let newValue = { $set: {} }; newValue.$set[fieldName + ".modifiedAt"] = Date.now(); newValue.$set[fieldName + ".modifiedBy"] = "anonymous"; newValue.$set[fieldName + ".transientValue"] = value; return collection.updateMany(filter, newValue, { upsert: true }); } functionCollection.publish = function publish (b) { console.log('publish') } functionCollection.close = function close () { return mongo.close(); } functionCollection.purge = function purge (collectionNames) { let promises = []; for (let i = 0; i < collectionNames.length; i++) { const collection = db.collection(collectionNames[i]); promises.push(collection.drop()); } return Promise.all(promises); }