forked from mikhail-angelov/mongo-unit
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
226 lines (202 loc) · 5.05 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
'use strict'
const Debug = require('debug')
const portfinder = require('portfinder')
const MongoClient = require('mongodb').MongoClient
const { MongoMemoryServer, MongoMemoryReplSet } = require('mongodb-memory-server')
const fs = require('fs')
const ps = require('ps-node')
const debug = Debug('mongo-unit-rs')
const dataFolder = '/.mongo-unit-rs'
const defaultTempDir = __dirname + dataFolder
const defaultMongoOpts = {
dbName: 'test',
dbpath: defaultTempDir,
port: 27017,
useReplicaSet: false
}
let mongod = null
let dbUrl = null
let client
let dbName
function runMongo(opts, port) {
const options = {
autoStart: false
}
if (opts.version) {
options.binary = { version: opts.version }
}
let startPromise
if (opts.useReplicaSet) {
options.instanceOpts = [
{
port: port,
dbPath: opts.dbpath,
storageEngine: 'wiredTiger',
}
]
options.replSet = {
dbName: opts.dbName,
storageEngine: 'wiredTiger'
}
mongod = new MongoMemoryReplSet(options)
startPromise = mongod.start().then(() => mongod.waitUntilRunning())
} else {
options.instance = {
port: port,
dbPath: opts.dbpath,
dbName: opts.dbName,
storageEngine: 'ephemeralForTest',
}
mongod = new MongoMemoryServer(options)
startPromise = mongod.start()
}
return startPromise
.then(() => {
return mongod.getDbName()
})
.then(dbName => {
dbUrl = 'mongodb://localhost:' + port + '/' + dbName
debug(`mongo is started on ${dbUrl}`)
return dbUrl
})
.then(url => MongoClient.connect(url, { useUnifiedTopology: true }))
.then(dbClient => {
client = dbClient
return dbUrl
})
.catch(err => console.error(err))
}
function start(opts) {
const mongo_opts = Object.assign(defaultMongoOpts, opts || {})
if (mongo_opts.verbose) {
Debug.enable('mongo-unit-rs')
Debug.enable('*')
}
if (dbUrl) {
return Promise.resolve(dbUrl)
} else {
makeSureTempDirExist(mongo_opts.dbpath, mongo_opts.useReplicaSet)
return makeSureOtherMongoProcessesKilled(mongo_opts.dbpath)
.then(() => getFreePort(mongo_opts.port))
.then(port => runMongo(mongo_opts, port))
}
}
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time))
}
function stop() {
return client
.close(true)
.then(() => mongod.stop())
.then(() => {
// mongodHelper && mongodHelper.mongoBin.childProcess.kill()
dbUrl = null
return delay(100) //this is small delay to make sure kill signal is sent
})
}
function getUrl() {
if (dbUrl) {
return dbUrl
} else {
throw new Error('Please start mongo-unit-rs first, then use this API')
}
}
function load(data) {
const db = client.db(dbName)
const queries = Object.keys(data).map(col => {
const collection = db.collection(col)
return collection.insertMany(data[col])
})
return Promise.all(queries)
}
function clean(data) {
const db = client.db(dbName)
const queries = Object.keys(data).map(col => {
const collection = db.collection(col)
return collection.drop()
})
return Promise.all(queries)
}
function drop() {
return client.db(dbName).dropDatabase()
}
function getFreePort(possiblePort) {
portfinder.basePort = possiblePort
return new Promise((resolve, reject) =>
portfinder.getPort((err, port) => {
if (err) {
debug(`cannot get free port: ${err}`)
reject(err)
} else {
resolve(port)
}
})
)
}
function makeSureTempDirExist(dir, useReplicaSet) {
try {
if (useReplicaSet) {
fs.rmdirSync(dir, { recursive: true })
}
fs.mkdirSync(dir)
} catch (e) {
if (e.code !== 'EEXIST') {
console.log('cannot create db folder', dir, e)
throw e
}
}
}
function makeSureOtherMongoProcessesKilled(dataFolder) {
return new Promise((resolve, reject) => {
ps.lookup(
{
psargs: ['-A'],
command: 'mongod',
arguments: dataFolder,
},
(err, resultList) => {
if (err) {
console.log('ps-node error', err)
return reject(err)
}
resultList.forEach(process => {
if (process) {
console.log(
'KILL PID: %s, COMMAND: %s, ARGUMENTS: %s',
process.pid,
process.command,
process.arguments
)
ps.kill(process.pid)
}
})
return resolve()
}
)
})
}
function initDb(url, data) {
const db = client.db(dbName)
const requests = Object.keys(data).map(col => {
const collection = db.collection(col)
return collection.insertMany(data[col])
})
return Promise.all(requests)
}
function dropDb(url) {
const db = client.db(dbName)
return db.collections().then(collections => {
const requests = collections.map(col => col.drop())
return Promise.all(requests)
})
}
module.exports = {
start,
stop,
getUrl,
load,
clean,
drop,
initDb,
dropDb,
}