-
Notifications
You must be signed in to change notification settings - Fork 6
/
db.js
68 lines (56 loc) · 1.57 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const fs = require('fs')
const { MongoClient } = require('mongodb')
const url = process.env.DB_MONGO_URL || 'mongodb://localhost:27017'
const dbName = process.env.DB_MONGO_NAME || 'adexMarket'
let db = null
function getMongoOptions(options) {
const mongoUseTls = process.env['DB_MONGO_USE_TLS'] || false
if (mongoUseTls) {
// Read the certificates
const mongoCa = [
fs.readFileSync(process.env['DB_MONGO_CA'] || 'rootCA.crt'),
]
const mongoCert = fs.readFileSync(
process.env['DB_MONGO_CERT'] || 'relayer.pem'
)
const mongoKey = fs.readFileSync(
process.env['DB_MONGO_KEY'] || 'relayer.pem'
)
const mongoReplset = process.env['DB_MONGO_REPLSET'] || false
const opts = {
sslValidate: true,
sslCA: mongoCa,
sslCert: mongoCert,
sslKey: mongoKey,
}
if (mongoReplset) {
options.replSet = opts
} else {
options.server = opts
}
}
return options
}
function connect() {
var options = getMongoOptions({ useNewUrlParser: true })
return MongoClient.connect(url, options).then(function(client) {
console.log(`Great success - mongo connected to ${dbName}`)
db = client.db(dbName)
createIndexes(db)
})
}
function getMongo() {
if (db) return db
else return null
}
function createIndexes(db) {
db.collection('adSlots').createIndex({ ipfs: 1 })
db.collection('adUnits').createIndex({ ipfs: 1 })
db.collection('campaigns').createIndex({ 'status.name': 1 })
db.collection('websites').createIndex(
{ publisher: 1, hostname: 1 },
{ unique: true }
)
db.collection('audiences').createIndex({ id: 1 })
}
module.exports = { connect, getMongo }