This repository has been archived by the owner on Jul 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
125 lines (104 loc) · 3.2 KB
/
index.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
const mongoose = require('mongoose')
const defaultLogger = {
log: console.log,
warn: console.warn,
info: console.info,
debug: console.debug,
error: console.error
}
let logger = defaultLogger
mongoose.Promise = global.Promise
applyListenersToConnection(mongoose.connection)
/** DEFAULT OPTIONS
*
* Can be overwritten.
* Check README
*
*/
const ssl = process.env['NODE_ENV'] ? process.env['NODE_ENV'] != 'development' : true
let defaultOptions = {
ssl,
sslValidate: false,
useNewUrlParser: true,
killProcessOnDisconnect: false // Behavior on disconnect
}
let currentOptions
/**
* Disconnect a mongo connection
*
* @returns {Promise<void>} Promise
*/
function disconnect() {
logger.debug('**** mongoose-harakiri: Disconnecting...')
if (mongoose.connection.readyState == 0) {
return logger.info('**** mongoose-harakiri: Connection is already closed.')
}
return mongoose.connection.close()
}
/**
* Connect to a mongodb
*
* @param {string} mongoConnectionString complete mongo connection string. e.g. user:password@mongodb:27017/database
* @param {object} [options] mongo client options; see README
*
* @returns {Promise<Mongoose>} Returns the connection
*/
function connect(mongoConnectionString, options = {}) {
// Generate options
currentOptions = { ...defaultOptions, ...options }
logger.info('**** mongoose-harakiri: Connecting.')
// Check if connection is already open
if (mongoose.connection.readyState > 0) {
logger.debug('**** mongoose-harakiri: Connection is already open.')
return Promise.resolve(mongoose.connection)
}
// Prepare mongoose options
const mongooseOptions = { ...currentOptions }
delete mongooseOptions.killProcessOnDisconnect
// Remove possible previous disconnect listener before connection attempt
mongoose.connection.removeListener('disconnected', disconnectListenerCallback)
// Connect
try {
mongoose.connect(mongoConnectionString, mongooseOptions)
} catch (error) {
logger.error('**** mongoose-harakiri: Failed connecting to the DB!')
logger.error(error)
process.exit(1)
}
// Apply disconnect listener after connection has been established
mongoose.connection.then(() => {
mongoose.connection.on('disconnected', disconnectListenerCallback)
})
return mongoose.connection
}
function applyListenersToConnection(connection) {
connection.on('connected', () => {
logger.info('**** mongoose-harakiri: Successfully connected.')
})
connection.on('reconnected', () => {
logger.info('**** mongoose-harakiri: Successfully reconnected.')
})
connection.on('error', (err) => {
logger.error('**** mongoose-harakiri: Mongoose connection error!')
logger.error(err)
process.exit(1)
})
}
function disconnectListenerCallback() {
logger.info('**** mongoose-harakiri: Default connection disconnected.')
if (currentOptions.killProcessOnDisconnect) return process.exit(1)
}
function setLogger(newLogger) {
const fns = Object.keys(defaultLogger)
fns.forEach(fn => {
if (typeof newLogger[fn] != 'function') {
throw new Error(`Logger should have functions called ${fns.join(', ')}. Try using a winston instance.`)
}
})
logger = newLogger
}
module.exports = {
connect,
disconnect,
setLogger
}