1
0
Fork 0
mirror of https://github.com/voltbonn/diversity.volt.link.git synced 2024-06-24 23:10:57 +00:00

added getMongoDbContext.js

This commit is contained in:
thomasrosen 2022-11-21 16:38:04 +01:00
parent 1b3fdcbc9c
commit 4e41788d20
2 changed files with 60 additions and 0 deletions

View file

@ -0,0 +1,58 @@
const isDevEnvironment = process.env.environment === 'dev' || false
const { MongoClient, ObjectId } = require('mongodb')
const _ContextChache_ = {}
function getMongoDbContext(){
return new Promise(async (resolve,reject)=>{
if (_ContextChache_.mongodb) {
resolve(_ContextChache_.mongodb)
}else{
const mongodb_uri = encodeURI(isDevEnvironment ? process.env.mongodb_uri_dev : process.env.mongodb_uri_prod) // test?retryWrites=true&w=majority
if (!mongodb_uri) {
reject('probably no mongodb rights')
}else{
MongoClient.connect(mongodb_uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(mongodb_client => {
const names = {
dbs: {
diversity: 'diversity',
},
collections: {
users: 'users',
answers: 'answers',
}
}
const dbs = {
diversity: mongodb_client.db(names.dbs.diversity),
}
const collections = {
users: dbs.diversity.collection(names.collections.users),
answers: dbs.diversity.collection(names.collections.answers),
}
_ContextChache_.mongodb = {
client: mongodb_client,
ObjectId,
ObjectID: ObjectId,
names,
dbs,
collections,
}
resolve(_ContextChache_.mongodb)
}).catch(error=>{
console.error(error)
reject('could not connect to mongodb')
})
}
}
})
}
module.exports = getMongoDbContext

View file

@ -1,5 +1,7 @@
require('dotenv').config()
// const getMongoDbContext = require('./getMongoDbContext.js')
// const isDevEnvironment = process.env.environment === 'dev' || false
const path = require('path')
const url = require('url')