-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
51 lines (44 loc) · 1.39 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
const MongoClient = require('mongodb').MongoClient;
const redis = require('redis')
const asyncRedis = require("async-redis")
const logger = require('./utils/logger');
const config = require('./config')
class DbInit {
async init() {
await this.connectMongo()
await this.connectRedis()
}
connectRedis() {
return new Promise((resolve, reject) => {
const url = `${config.redis.connectionString}:${config.redis.port}`
const redisClient = asyncRedis.createClient(url)
redisClient.on('ready', () => {
this.redis = redisClient
logger.db.info('Connected to redis cache')
resolve();
});
redisClient.on('error', err => {
reject(`Error connecting to redis - ${err}`)
});
});
}
connectMongo() {
return new Promise((resolve, reject) => {
const url = `${config.mongodb.connectionString}:${config.mongodb.port}`
const mongoClient = new MongoClient(url, { useNewUrlParser: true })
mongoClient.connect((err) => {
if (!err) {
this.mongoDb = mongoClient.db(config.mongodb.dbName)
logger.db.info(`Connected to database - ${config.mongodb.dbName}`)
process.on('SIGINT', () => {
MongoClient.close();
})
resolve()
} else {
reject(`Error connecting to MongoDB - ${err}`)
}
})
})
}
}
module.exports = new DbInit()