This repository has been archived by the owner on Feb 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 106
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(mock): support a means of consistently cleaning up mock servers
NODE-1132
- Loading branch information
Showing
1 changed file
with
32 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,42 @@ | ||
var Server = require('./lib/server'); | ||
|
||
const cleanup = (servers, spy, callback) => { | ||
if (!Array.isArray(servers)) { | ||
throw new Error('First argument must be an array of mock servers'); | ||
} | ||
|
||
if (spy) { | ||
const alreadyDrained = spy.connectionCount() === 0; | ||
const finish = () => { | ||
callback(null, null); | ||
}; | ||
|
||
if (!alreadyDrained) { | ||
spy.once('drained', () => finish()); | ||
} | ||
|
||
const cleanupPromise = Promise.all(servers.map(server => server.destroy())).catch(err => | ||
callback(err, null) | ||
); | ||
|
||
if (alreadyDrained) { | ||
cleanupPromise.then(() => finish()); | ||
} | ||
} else { | ||
Promise.all(servers.map(server => server.destroy())) | ||
.then(() => callback(null, null)) | ||
.catch(err => callback(err, null)); | ||
} | ||
}; | ||
|
||
/* | ||
* Main module | ||
*/ | ||
module.exports = { | ||
createServer: function(port, host, options) { | ||
options = options || {}; | ||
return new Server(port, host, options).start(); | ||
} | ||
}, | ||
|
||
cleanup: cleanup | ||
}; |