-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
190 lines (148 loc) · 4.84 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
const { MongoClient, ObjectId } = require('mongodb')
const net = require('net')
const debug = require('debug')('mongoprime')
const uniqueTempDir = require('unique-temp-dir')
const MongodbPrebuilt = require('mongodb-prebuilt')
const process = require('process')
const getPort = require('get-port')
const MongoWireProtocol = require('mongo-wire-protocol')
const uuid = require('uuid')
let options = {
fixtures: {}, // Fixture collection
host: '127.0.0.1', // Proxy host
port: 27018, // Proxy port
ignore: ['system', 'admin', 'local'], // Collections to ignore
path: null, // Path for mongo metadata - defaults to randomly generated systm tmp dir
mongo: null // Mongo port - randomly generated
}
let initialized = false
let connections = {}
let primed = []
const startProxy = async () => {
const server = net.createServer()
server.on('connection', (socket) => {
debug('New connection received')
var request = new MongoWireProtocol()
socket.on('data', async (chunk) => {
if (request.finished) {
request = new MongoWireProtocol()
}
request.parse(chunk)
if (!request.finished) {
}
const database = request.fullCollectionName.replace('.$cmd', '')
await primeDatabase(database)
forwardRequest(socket, chunk, database)
})
socket.on('error', error => {
console.error(error)
})
socket.on('close', () => {
debug('Connection closed')
})
})
server.on('listening', () => {
debug('Server started')
})
server.listen({port: options.port, host: options.host})
}
const generateURL = () => {
return {
host: `mongodb://${options.host}:${options.port}`,
db: uuid()
}
}
const forwardRequest = (socket, chunk, database) => {
const serviceSocket = new net.Socket()
serviceSocket.connect(options.mongo, options.host, function () {
debug(`Forwarding data to ${database}`)
serviceSocket.write(chunk)
})
serviceSocket.on('end', function () {
})
serviceSocket.on('data', function (data) {
debug(`Receiving data from ${database}`)
socket.write(data)
// socket.end()
})
}
const primeDatabase = async (database) => {
if (!!~options.ignore.indexOf(database) || !!~primed.indexOf(database)) return
primed.push(database)
debug(`Priming ${database}`)
await clearCollections(database)
await loadFixtures(database)
}
const initProxy = async (params) => {
if (initialized) return
options = Object.assign(options, params)
options.mongo = await getPort()
options.path = options.path || uniqueTempDir({ create: true })
await startServer()
await startProxy()
process.env.MONGO_PRIMER_DB_PORT = options.port
process.env.MONGO_PRIMER_DB_HOST = options.host
initialized = true
}
const getUri = (databaseName) => {
return {
host: 'mongodb://' + options.host + ':' + options.mongo,
db: databaseName
}
}
const clearCollections = async (database) => {
const db = await getConnection(database)
const names = await listCollections(database)
const filtered = Object.keys(options.fixtures).filter(c => ~names.indexOf(c))
return Promise.all(filtered.map(name => {
return db.collection(name).drop()
}))
}
const startServer = async () => {
const mongodHelper = new MongodbPrebuilt.MongodHelper(['--bind_ip', options.host, '--port', options.mongo, '--dbpath', options.path, '--storageEngine', 'ephemeralForTest'])
await mongodHelper.run()
}
const getConnection = async (database) => {
if (connections[database]) {
debug(`Reusing ${database} connection`)
return Promise.resolve(connections[database])
} else {
const { host, db } = getUri(database)
const con = await MongoClient.connect(host)
connections[database] = con.db(db)
return connections[database]
}
}
const stopServer = async () => {
Object.keys(connections).map(databaseName => {
connections[databaseName].close()
})
return new MongodbPrebuilt.MongoBins('mongo', ['--port', options.mongo, '--eval', "db.getSiblingDB('admin').shutdownServer()"]).run()
}
const closeAll = async (database) => {
const db = await getConnection(database)
db.stop()
}
const listCollections = async (database) => {
const db = await getConnection(database)
const names = await db.listCollections().toArray()
return names.map(c => {
return c.name
}).filter(c => {
return !c.match(options.ignore)
})
}
const loadFixtures = async (database) => {
const db = await getConnection(database)
const promises = Object.keys(options.fixtures).map(name => {
const items = options.fixtures[name]
// Ensure there is something else we get and Invalid Operation, no operations specified error
if (items.length) { return db.collection(name).insert(items) }
})
return Promise.all(promises)
}
exports.generateURL = generateURL
exports.initProxy = initProxy
exports.stopServer = stopServer
exports.closeAll = closeAll
exports.ObjectId = ObjectId