-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
204 lines (184 loc) · 5.51 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
const mongoose = require('mongoose');
const envOpts = {};
// Todo: Extend documentation with links where to find these options.
const DEFAULT_CONFIG = {
debug: false,
host: 'localhost',
port: 27017,
database: '',
connectOptions: {
db: {},
server: {
auto_reconnect: true,
socketOptions: {
keepAlive: 1,
connectTimeoutMS: 30000
}
},
replset: {
socketOptions: {
keepAlive: 1,
connectTimeoutMS: 30000
}
},
user: {},
pass: {},
auth: {},
mongos: {}
}
};
/**
* @class MongooseConnection
* @name MongooseConnection
* @api public
*/
class MongooseConnection {
/**
* Define a configuration object to pass to the constructor.
*
* If no options are defined, the default options will be used:
*
*
* ```js
* // Default Options:
* const defaultOpts = {
* debug: false,
* host: 'localhost',
* port: 27017,
* database: '',
* connectOptions: {
* db: {},
* server: {
* auto_reconnect: true
* },
* replset: {},
* user: {},
* pass: {},
* auth: {},
* mongos: {}
* }
* };
* ```
* See [index.js => defaultOpts](index.js) for more information about the current default options.
*
*
* @name Configuration
*
* @param {Object} `opts` - Options to pass in.
* @param {Boolean} `opts.debug` - Whether MongoDB runs in debug mode or not.
* @param {String} `opts.host` - The MongoDBhost, defaults to `localhost`. See the mongodb [connection string spec](https://docs.mongodb.com/manual/reference/connection-string/) for more details.
* @param {Number} `opts.port` - The MongoDB port, defaults to `27017`. See the mongodb [connection string spec](https://docs.mongodb.com/manual/reference/connection-string/) for more details.
* @param {String} `opts.database` - The MongoDB database, defaults to `admin`. See the mongodb [connection string spec](https://docs.mongodb.com/manual/reference/connection-string/) for more details.
* @param {Object} `opts.connectOptions` - The MongoDB connection properties, being passed through to the native MongoDB driver. See [mongoose' documentation](http://mongoosejs.com/docs/connections.html), resp. [MongoDB's native driver for node.js' documentation](https://github.com/mongodb/node-mongodb-native) for more details.
*
* @api public
*/
/**
* Initialize a new MongooseConnection.
*
* @name .constructor()
* @constructor
* @param {Configuration} opts - Options to initialize _MongooseConnection_.
* @api public
*/
constructor(opts) {
this.config = Object.assign(envOpts, DEFAULT_CONFIG, opts);
this.connection = null;
/**
* Returns the default options of mongoose-connection-promise
*
* @name DEFAULT_CONFIG
* @type object
* @api public
*/
this.DEFAULT_CONFIG = DEFAULT_CONFIG;
mongoose.Promise = global.Promise;
}
/**
* Connect mongoose to the given instance of MongoDB.
*
* @name .connect()
* @returns {Promise}
* @api public
*/
connect() {
return new Promise((resolve, reject) => {
const options = {};
if (!this.connection) {
this.connection = mongoose.connection;
}
mongoose.connect(this._getMongoUri(), options)
.then(() => resolve(this.connection))
.catch(err => reject(err));
});
}
/**
* Get an existing connection or create a new one.
*
* In contrary to `.connect()` this method will not create a new connection if MongooseConnection is already connected,
* but the existing connection will be re-used and returned.
*
* @name .get()
* @returns {Promise<NavtiveConnection,Error>} - Returns the connection to MongoDB.
* @api public
*/
get() {
if (this.isConnected()) {
return Promise.resolve(this.connection);
}
return this.connect();
}
/**
* Disconnects all mongoose connections.
*
* @name .disconnect()
* @returns {Promise<void,Error>}
* @api public
*/
disconnect() {
return mongoose.disconnect();
}
/**
* Indicates whether there is a current and ready-to-use mongoose connection.
*
* @name .isConnected()
* @returns {boolean}
* @api public
*/
isConnected() {
return this.connection && this.connection.readyState === 1;
}
/**
* Return the default options (DEPRECATED).
*
* @name .defaultOptions()
* @returns object
* @api public
* @deprecated
*/
defaultOptions() {
console.error('.defaultOptions() is deprecated, use .DEFAULT_OPTIONS instead.');
return DEFAULT_CONFIG;
}
/* -------------------------------------------------------------------------------------- */
/* INTERNAL HELPER METHODS */
/* -------------------------------------------------------------------------------------- */
_getMongoUri() {
let c = 'mongodb://';
c += this._getMongoUri_UserPwd();
c += this._getMongoUri_Hosts();
c += this._getMongoUri_Database();
return c;
}
_getMongoUri_UserPwd() {
return (this.config.username && this.config.password) ? this.config.username + ':' + this.config.password + '@' : '';
}
_getMongoUri_Hosts() {
// Todo: Allow multiple hosts according to https://docs.mongodb.com/manual/reference/connection-string/
return this.config.host + ':' + this.config.port;
}
_getMongoUri_Database() {
return (this.config.database) ? `/${this.config.database}` : '';
}
}
module.exports = MongooseConnection;