Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
207 lines (186 loc) · 4.52 KB
/
Copy pathindex.js
File metadata and controls
207 lines (186 loc) · 4.52 KB
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
'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')
const dataFolder = '/.mongo-unit'
const defaultTempDir = __dirname + dataFolder
const defaultMongoOpts = {
dbName: 'test',
dbpath: defaultTempDir,
port: 27017,
useReplicaSet: false
}
let mongod = null
let dbUrl = null
let client
let dbName
async function runMongo(opts, port) {
const options = {
autoStart: false
}
if (opts.version) {
options.binary = { version: opts.version }
}
if (opts.useReplicaSet) {
options.instanceOpts = [
{
port: port,
dbPath: opts.dbpath,
storageEngine: 'wiredTiger',
}
]
options.replSet = {
dbName: opts.dbName,
storageEngine: 'wiredTiger'
}
mongod = await MongoMemoryReplSet.create(options)
await mongod.waitUntilRunning()
} else {
options.instance = {
port: port,
dbPath: opts.dbpath,
dbName: opts.dbName,
storageEngine: 'ephemeralForTest',
}
mongod = await MongoMemoryServer.create(options)
await mongod.ensureInstance()
}
dbUrl = mongod.getUri()
client = await MongoClient.connect(dbUrl, { useUnifiedTopology: true })
return dbUrl
}
function start(opts) {
const mongo_opts = Object.assign(defaultMongoOpts, opts || {})
if (mongo_opts.verbose) {
Debug.enable('mongo-unit')
Debug.enable('*')
}
dbName = mongo_opts.dbName;
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))
}
async function stop() {
await client.close(true)
await mongod.stop(true)
dbUrl = null
await 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 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 (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true })
}
fs.mkdirSync(dir)
} catch (e) {
console.log('cannot create db folder', dir, e)
if (e.code !== 'EEXIST') {
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(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() {
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,
}