dashboards_mirror_survey_stack
Version:
Library allowing to retrieve, reorganize and keep up to date SurveyStack data in a mongoDB mirror as well as serving it efficiently.
72 lines (64 loc) • 2.64 kB
JavaScript
const { MongoClient, ObjectId } = require('mongodb');
async function createAView( { connectionURL, viewName, db="dashboards", sourceCollection, aggregationPipeline } ) {
const client = new MongoClient(connectionURL);
let viewCreation = {
viewName: viewName
};
try {
// we need to erase the view if it previously existed first, as is seems there is no way of updating the view instead
await client.connect();
let drop = await client
.db(db)
.dropCollection(viewName)
;
} catch(e) {
if ( e.code == 26 ) {
// an error 26 will be generated when the namespace we want to drop isn't found, meaning the collection is new
viewCreation.previouslyExisted = false;
} else {
viewCreation.previouslyExisted = true;
viewCreation.cleaningError = e;
};
}
;
try {
// once the preexistence problem is dealth with, we can directly create the view
viewCreation.result = await client
.db(db)
.createCollection(
viewName,
{
viewOn: sourceCollection,
pipeline: aggregationPipeline
}
);
viewCreation.errored = false;
} catch(error) {
viewCreation.error = error;
viewCreation.errored = true;
} finally {
await client.close();
};
return viewCreation;
};
// let experiment1 = createAView( connectionURL, dataExplorerView.name, "dashboards",dataExplorerView.sourceCollection, dataExplorerView.pipeline ).catch(console.error);
/**
* Creates a set of views, based on provided object with the needed parameters
* @param { [name:string, sourceCollection:string, pipeline: mongoDBPipeline] } viewsList -- List of objects describing views, each one provides the target name, the pipeline and the source colletion.
* @param {string} connectionURL -- MongoDB connection URI.
* @param {string} db -- Database Name.
* @returns {}
*/
async function createAllViews( { viewsList, connectionURL, db = "dashboards" } ) {
let index = 0;
let results = [];
while( index < viewsList.length ) {
let currentView = viewsList[index];
let currentResult = await createAView( { connectionURL:connectionURL, viewName: currentView.name, db:db, sourceCollection:currentView.sourceCollection, aggregationPipeline:currentView.pipeline } );
results.push(currentResult);
index ++;
};
return results;
};
exports.createAllViews = createAllViews;
exports.createAView = createAView;