mirror of
https://github.com/voltbonn/diversity.volt.link.git
synced 2024-06-28 08:50:56 +00:00
added getMongoDbContext.js
This commit is contained in:
parent
1b3fdcbc9c
commit
4e41788d20
58
backend/getMongoDbContext.js
Normal file
58
backend/getMongoDbContext.js
Normal 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
|
|
@ -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')
|
||||
|
|
Loading…
Reference in a new issue