Socket
Socket
Sign inDemoInstall

mongodb-memory-server

Package Overview
Dependencies
Maintainers
1
Versions
345
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mongodb-memory-server - npm Package Compare versions

Comparing version 2.1.0 to 2.2.0

lib/__tests__/multipleDB-test.js

40

lib/index.js

@@ -1,2 +0,2 @@

'use strict';
"use strict";

@@ -6,21 +6,31 @@ Object.defineProperty(exports, "__esModule", {

});
exports.MongoBinary = exports.MongoInstance = exports.MongoMemoryServer = undefined;
Object.defineProperty(exports, "MongoMemoryServer", {
enumerable: true,
get: function get() {
return _MongoMemoryServer.default;
}
});
Object.defineProperty(exports, "MongoInstance", {
enumerable: true,
get: function get() {
return _MongoInstance.default;
}
});
Object.defineProperty(exports, "MongoBinary", {
enumerable: true,
get: function get() {
return _MongoBinary.default;
}
});
exports.default = void 0;
var _MongoMemoryServer = require('./MongoMemoryServer');
var _MongoMemoryServer = _interopRequireDefault(require("./MongoMemoryServer"));
var _MongoMemoryServer2 = _interopRequireDefault(_MongoMemoryServer);
var _MongoInstance = _interopRequireDefault(require("./util/MongoInstance"));
var _MongoInstance = require('./util/MongoInstance');
var _MongoBinary = _interopRequireDefault(require("./util/MongoBinary"));
var _MongoInstance2 = _interopRequireDefault(_MongoInstance);
var _MongoBinary = require('./util/MongoBinary');
var _MongoBinary2 = _interopRequireDefault(_MongoBinary);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _MongoMemoryServer2.default;
exports.MongoMemoryServer = _MongoMemoryServer2.default;
exports.MongoInstance = _MongoInstance2.default;
exports.MongoBinary = _MongoBinary2.default;
var _default = _MongoMemoryServer.default;
exports.default = _default;

@@ -1,2 +0,2 @@

'use strict';
"use strict";

@@ -6,54 +6,56 @@ Object.defineProperty(exports, "__esModule", {

});
exports.default = void 0;
let generateDbName = (() => {
var _ref = _asyncToGenerator(function* (dbName) {
return dbName || (0, _v2.default)();
});
var _v = _interopRequireDefault(require("uuid/v4"));
return function generateDbName(_x) {
return _ref.apply(this, arguments);
};
})();
var _tmp = _interopRequireDefault(require("tmp"));
let generateConnectionString = (() => {
var _ref2 = _asyncToGenerator(function* (port, dbName) {
return `mongodb://127.0.0.1:${port}/${dbName}`;
});
var _getPort = _interopRequireDefault(require("get-port"));
return function generateConnectionString(_x2, _x3) {
return _ref2.apply(this, arguments);
};
})();
var _debug = _interopRequireDefault(require("debug"));
var _v = require('uuid/v4');
var _MongoInstance = _interopRequireDefault(require("./util/MongoInstance"));
var _v2 = _interopRequireDefault(_v);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _tmp = require('tmp');
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var _tmp2 = _interopRequireDefault(_tmp);
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
var _getPort = require('get-port');
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var _getPort2 = _interopRequireDefault(_getPort);
_tmp.default.setGracefulCleanup();
var _debug = require('debug');
function generateDbName(_x) {
return _generateDbName.apply(this, arguments);
}
var _debug2 = _interopRequireDefault(_debug);
function _generateDbName() {
_generateDbName = _asyncToGenerator(function* (dbName) {
return dbName || (0, _v.default)();
});
return _generateDbName.apply(this, arguments);
}
var _MongoInstance = require('./util/MongoInstance');
function generateConnectionString(_x2, _x3) {
return _generateConnectionString.apply(this, arguments);
}
var _MongoInstance2 = _interopRequireDefault(_MongoInstance);
function _generateConnectionString() {
_generateConnectionString = _asyncToGenerator(function* (port, dbName) {
return `mongodb://127.0.0.1:${port}/${dbName}`;
});
return _generateConnectionString.apply(this, arguments);
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class MongoMemoryServer {
constructor(opts = {}) {
_defineProperty(this, "isRunning", false);
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
_defineProperty(this, "runningInstance", void 0);
_tmp2.default.setGracefulCleanup();
_defineProperty(this, "opts", void 0);
class MongoMemoryServer {
_defineProperty(this, "debug", void 0);
constructor(opts = {}) {
this.isRunning = false;
this.opts = opts;

@@ -67,5 +69,5 @@ if (!this.opts.instance) this.opts.instance = {};

}
};
}; // autoStart by default
// autoStart by default
if (!opts.hasOwnProperty('autoStart') || opts.autoStart) {

@@ -85,19 +87,19 @@ this.debug('Autostarting MongoDB instance...');

_this.runningInstance = _this._startUpInstance().catch(function (err) {
_this.runningInstance = _this._startUpInstance().catch(err => {
if (err.message === 'Mongod shutting down' || err === 'Mongod shutting down') {
_this.debug(`Mongodb does not started. Trying to start on another port one more time...`);
_this.opts.instance.port = null;
return _this._startUpInstance();
}
throw err;
}).catch(function (err) {
}).catch(err => {
if (!_this.opts.debug) {
throw new Error(`${err.message}\n\nUse debug option for more info: ` + `new MongoMemoryServer({ debug: true })`);
}
throw err;
});
return _this.runningInstance.then(function () {
return true;
});
return _this.runningInstance.then(() => true);
})();

@@ -112,6 +114,7 @@ }

let tmpDir;
const instOpts = _this2.opts.instance;
data.port = yield (0, _getPort2.default)({ port: instOpts.port });
_this2.debug = (0, _debug2.default)(`Mongo[${data.port}]`);
data.port = yield (0, _getPort.default)({
port: instOpts.port
});
_this2.debug = (0, _debug.default)(`Mongo[${data.port}]`);
_this2.debug.enabled = !!_this2.opts.debug;

@@ -121,14 +124,18 @@ data.dbName = yield generateDbName(instOpts.dbName);

data.storageEngine = instOpts.storageEngine || 'ephemeralForTest';
if (instOpts.dbPath) {
data.dbPath = instOpts.dbPath;
} else {
tmpDir = _tmp2.default.dirSync({ prefix: 'mongo-mem-', unsafeCleanup: true });
tmpDir = _tmp.default.dirSync({
prefix: 'mongo-mem-',
unsafeCleanup: true
});
data.dbPath = tmpDir.name;
}
_this2.debug(`Starting MongoDB instance with following options: ${JSON.stringify(data)}`);
_this2.debug(`Starting MongoDB instance with following options: ${JSON.stringify(data)}`); // Download if not exists mongo binaries in ~/.mongodb-prebuilt
// After that startup MongoDB instance
// Download if not exists mongo binaries in ~/.mongodb-prebuilt
// After that startup MongoDB instance
const instance = yield _MongoInstance2.default.run({
const instance = yield _MongoInstance.default.run({
instance: {

@@ -147,3 +154,2 @@ port: data.port,

data.tmpDir = tmpDir;
return data;

@@ -157,10 +163,9 @@ })();

return _asyncToGenerator(function* () {
var _ref3 = yield _this3.getInstanceData();
const _ref = yield _this3.getInstanceData(),
instance = _ref.instance,
port = _ref.port,
tmpDir = _ref.tmpDir;
const instance = _ref3.instance,
port = _ref3.port,
tmpDir = _ref3.tmpDir;
_this3.debug(`Shutdown MongoDB server on port ${port} with pid ${instance.getPid() || ''}`);
_this3.debug(`Shutdown MongoDB server on port ${port} with pid ${instance.getPid() || ''}`);
yield instance.kill();

@@ -170,2 +175,3 @@

_this3.debug(`Removing tmpDir ${tmpDir.name}`);
tmpDir.removeCallback();

@@ -186,2 +192,3 @@ }

}
throw new Error('Database instance is not running. You should start database by calling start() method. BTW it should start automatically if opts.autoStart!=false. Also you may provide opts.debug=true for more info.');

@@ -195,9 +202,7 @@ })();

return _asyncToGenerator(function* () {
var _ref4 = yield _this5.getInstanceData();
const _ref2 = yield _this5.getInstanceData(),
uri = _ref2.uri,
port = _ref2.port; // IF true OR string
const uri = _ref4.uri,
port = _ref4.port;
// IF true OR string
if (otherDbName) {

@@ -207,4 +212,5 @@ if (typeof otherDbName === 'string') {

return generateConnectionString(port, otherDbName);
}
// generate new random db name
} // generate new random db name
return generateConnectionString(port, (yield generateDbName()));

@@ -229,6 +235,5 @@ }

return _asyncToGenerator(function* () {
var _ref5 = yield _this7.getInstanceData();
const _ref3 = yield _this7.getInstanceData(),
port = _ref3.port;
const port = _ref5.port;
return port;

@@ -242,6 +247,5 @@ })();

return _asyncToGenerator(function* () {
var _ref6 = yield _this8.getInstanceData();
const _ref4 = yield _this8.getInstanceData(),
dbPath = _ref4.dbPath;
const dbPath = _ref6.dbPath;
return dbPath;

@@ -255,10 +259,11 @@ })();

return _asyncToGenerator(function* () {
var _ref7 = yield _this9.getInstanceData();
const _ref5 = yield _this9.getInstanceData(),
dbName = _ref5.dbName;
const dbName = _ref7.dbName;
return dbName;
})();
}
}
exports.default = MongoMemoryServer;
"use strict";
/* eslint-disable */
/*

@@ -10,3 +11,2 @@ make sure every few seconds that parent is still alive

*/
var parentPid = parseInt(process.argv[2], 10);

@@ -23,9 +23,9 @@ var childPid = parseInt(process.argv[3], 10);

process.kill(childPid);
} catch (ee) {
// doesnt matter if it is dead
} catch (ee) {// doesnt matter if it is dead
}
process.exit();
}
} // if child dead
// if child dead
try {

@@ -32,0 +32,0 @@ process.kill(childPid, 0);

@@ -1,2 +0,2 @@

'use strict';
"use strict";

@@ -6,29 +6,23 @@ Object.defineProperty(exports, "__esModule", {

});
exports.default = void 0;
var _os = require('os');
var _os = _interopRequireDefault(require("os"));
var _os2 = _interopRequireDefault(_os);
var _path = _interopRequireDefault(require("path"));
var _path = require('path');
var _lockfile = _interopRequireDefault(require("lockfile"));
var _path2 = _interopRequireDefault(_path);
var _mkdirp = _interopRequireDefault(require("mkdirp"));
var _lockfile = require('lockfile');
var _MongoBinaryDownload = _interopRequireDefault(require("./MongoBinaryDownload"));
var _lockfile2 = _interopRequireDefault(_lockfile);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _mkdirp = require('mkdirp');
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
var _mkdirp2 = _interopRequireDefault(_mkdirp);
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var _MongoBinaryDownload = require('./MongoBinaryDownload');
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var _MongoBinaryDownload2 = _interopRequireDefault(_MongoBinaryDownload);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
class MongoBinary {
static getPath(opts = {}) {

@@ -38,13 +32,20 @@ var _this = this;

return _asyncToGenerator(function* () {
var _opts$downloadDir = opts.downloadDir;
const downloadDir = _opts$downloadDir === undefined ? _path2.default.resolve(_os2.default.homedir(), '.mongodb-binaries') : _opts$downloadDir;
var _opts$platform = opts.platform;
const platform = _opts$platform === undefined ? _os2.default.platform() : _opts$platform;
var _opts$arch = opts.arch;
const arch = _opts$arch === undefined ? _os2.default.arch() : _opts$arch;
var _opts$version = opts.version;
const version = _opts$version === undefined ? 'latest' : _opts$version;
var _process$env, _process$env2, _process$env3, _process$env4;
const defaultOptions = {
downloadDir: ((_process$env = process.env) === null || _process$env === void 0 ? void 0 : _process$env.MONGOMS_DOWNLOAD_DIR) || _path.default.resolve(_os.default.homedir(), '.mongodb-binaries'),
platform: ((_process$env2 = process.env) === null || _process$env2 === void 0 ? void 0 : _process$env2.MONGOMS_PLATFORM) || _os.default.platform(),
arch: ((_process$env3 = process.env) === null || _process$env3 === void 0 ? void 0 : _process$env3.MONGOMS_ARCH) || _os.default.arch(),
version: ((_process$env4 = process.env) === null || _process$env4 === void 0 ? void 0 : _process$env4.MONGOMS_VERSION) || 'latest',
debug: typeof process.env.MONGOMS_DEBUG === 'string' ? ['1', 'on', 'yes', 'true'].indexOf(process.env.MONGOMS_DEBUG.toLowerCase()) !== -1 : false
};
const _Object$assign = Object.assign({}, defaultOptions, opts),
downloadDir = _Object$assign.downloadDir,
platform = _Object$assign.platform,
arch = _Object$assign.arch,
version = _Object$assign.version;
let debug;
if (opts.debug) {

@@ -57,3 +58,4 @@ if (opts.debug.call && typeof opts.debug === 'function' && opts.debug.apply) {

} else {
debug = function debug(msg) {}; // eslint-disable-line
debug = msg => {}; // eslint-disable-line
}

@@ -65,4 +67,4 @@

// create downloadDir if not exists
yield new Promise(function (resolve, reject) {
(0, _mkdirp2.default)(downloadDir, function (err) {
yield new Promise((resolve, reject) => {
(0, _mkdirp.default)(downloadDir, err => {
if (err) reject(err);else resolve();

@@ -72,7 +74,7 @@ });

const lockfile = _path2.default.resolve(downloadDir, `${version}.lock`);
const lockfile = _path.default.resolve(downloadDir, `${version}.lock`); // wait lock
// wait lock
yield new Promise(function (resolve, reject) {
_lockfile2.default.lock(lockfile, {
yield new Promise((resolve, reject) => {
_lockfile.default.lock(lockfile, {
wait: 120000,

@@ -83,10 +85,9 @@ pollPeriod: 100,

retryWait: 100
}, function (err) {
}, err => {
if (err) reject(err);else resolve();
});
});
}); // again check cache, maybe other instance resolve it
// again check cache, maybe other instance resolve it
if (!_this.cache[version]) {
const downloader = new _MongoBinaryDownload2.default({
const downloader = new _MongoBinaryDownload.default({
downloadDir,

@@ -97,9 +98,8 @@ platform,

});
downloader.debug = debug;
_this.cache[version] = yield downloader.getMongodPath();
}
} // remove lock
// remove lock
_lockfile2.default.unlock(lockfile, function (err) {
_lockfile.default.unlock(lockfile, err => {
debug(err ? `MongoBinary: Error when removing download lock ${err}` : `MongoBinary: Download lock removed`);

@@ -120,6 +120,10 @@ });

}
return false;
}
}
exports.default = MongoBinary;
MongoBinary.cache = {};
_defineProperty(MongoBinary, "cache", {});

@@ -1,2 +0,2 @@

'use strict';
"use strict";

@@ -6,51 +6,54 @@ Object.defineProperty(exports, "__esModule", {

});
exports.default = void 0;
var _os = require('os');
var _os = _interopRequireDefault(require("os"));
var _os2 = _interopRequireDefault(_os);
var _url = _interopRequireDefault(require("url"));
var _url = require('url');
var _path = _interopRequireDefault(require("path"));
var _url2 = _interopRequireDefault(_url);
var _fs = _interopRequireDefault(require("fs"));
var _path = require('path');
var _md5File = _interopRequireDefault(require("md5-file"));
var _path2 = _interopRequireDefault(_path);
var _https = _interopRequireDefault(require("https"));
var _fs = require('fs');
var _httpsProxyAgent = _interopRequireDefault(require("https-proxy-agent"));
var _fs2 = _interopRequireDefault(_fs);
var _decompress = _interopRequireDefault(require("decompress"));
var _md5File = require('md5-file');
var _MongoBinaryDownloadUrl = _interopRequireDefault(require("./MongoBinaryDownloadUrl"));
var _md5File2 = _interopRequireDefault(_md5File);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _https = require('https');
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
var _https2 = _interopRequireDefault(_https);
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var _httpsProxyAgent = require('https-proxy-agent');
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var _httpsProxyAgent2 = _interopRequireDefault(_httpsProxyAgent);
class MongoBinaryDownload {
constructor({
platform,
arch,
downloadDir,
version,
debug
}) {
_defineProperty(this, "debug", void 0);
var _decompress = require('decompress');
_defineProperty(this, "dlProgress", void 0);
var _decompress2 = _interopRequireDefault(_decompress);
_defineProperty(this, "downloadDir", void 0);
var _MongoBinaryDownloadUrl = require('./MongoBinaryDownloadUrl');
_defineProperty(this, "arch", void 0);
var _MongoBinaryDownloadUrl2 = _interopRequireDefault(_MongoBinaryDownloadUrl);
_defineProperty(this, "version", void 0);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_defineProperty(this, "platform", void 0);
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/* eslint-disable class-methods-use-this */
class MongoBinaryDownload {
constructor({ platform, arch, downloadDir, version, debug }) {
this.platform = platform || _os2.default.platform();
this.arch = arch || _os2.default.arch();
this.platform = platform || _os.default.platform();
this.arch = arch || _os.default.arch();
this.version = version || 'latest';
this.downloadDir = _path2.default.resolve(downloadDir || 'mongodb-download');
this.downloadDir = _path.default.resolve(downloadDir || 'mongodb-download');
this.dlProgress = {

@@ -79,3 +82,5 @@ current: 0,

const binaryName = _this.platform === 'win32' ? 'mongod.exe' : 'mongod';
const mongodPath = _path2.default.resolve(_this.downloadDir, _this.version, binaryName);
const mongodPath = _path.default.resolve(_this.downloadDir, _this.version, binaryName);
if (_this.locationExists(mongodPath)) {

@@ -87,4 +92,5 @@ return mongodPath;

yield _this.extract(mongoDBArchive);
_fs2.default.unlinkSync(mongoDBArchive);
_fs.default.unlinkSync(mongoDBArchive);
if (_this.locationExists(mongodPath)) {

@@ -102,3 +108,3 @@ return mongodPath;

return _asyncToGenerator(function* () {
const mbdUrl = new _MongoBinaryDownloadUrl2.default({
const mbdUrl = new _MongoBinaryDownloadUrl.default({
platform: _this2.platform,

@@ -109,4 +115,4 @@ arch: _this2.arch,

if (!_fs2.default.existsSync(_this2.downloadDir)) {
_fs2.default.mkdirSync(_this2.downloadDir);
if (!_fs.default.existsSync(_this2.downloadDir)) {
_fs.default.mkdirSync(_this2.downloadDir);
}

@@ -116,6 +122,4 @@

const mongoDBArchive = yield _this2.download(downloadUrl);
const mongoDBArchiveMd5 = yield _this2.download(`${downloadUrl}.md5`);
yield _this2.checkMd5(mongoDBArchiveMd5, mongoDBArchive);
return mongoDBArchive;

@@ -127,6 +131,9 @@ })();

return _asyncToGenerator(function* () {
const signatureContent = _fs2.default.readFileSync(mongoDBArchiveMd5).toString('UTF-8');
const signatureContent = _fs.default.readFileSync(mongoDBArchiveMd5).toString('UTF-8');
const m = signatureContent.match(/(.*?)\s/);
const md5Remote = m ? m[1] : null;
const md5Local = _md5File2.default.sync(mongoDBArchive);
const md5Local = _md5File.default.sync(mongoDBArchive);
if (md5Remote !== md5Local) {

@@ -144,3 +151,3 @@ throw new Error('MongoBinaryDownload: md5 check is failed');

const urlObject = _url2.default.parse(downloadUrl);
const urlObject = _url.default.parse(downloadUrl);

@@ -152,6 +159,6 @@ const downloadOptions = {

method: 'GET',
agent: proxy ? new _httpsProxyAgent2.default(proxy) : undefined
agent: proxy ? new _httpsProxyAgent.default(proxy) : undefined
};
const filename = (urlObject.pathname || '').split('/').pop();
const filename = (urlObject.pathname || '').split('/').pop();
if (!filename) {

@@ -161,4 +168,6 @@ throw new Error(`MongoBinaryDownload: missing filename for url ${downloadUrl}`);

const downloadLocation = _path2.default.resolve(_this3.downloadDir, filename);
const tempDownloadLocation = _path2.default.resolve(_this3.downloadDir, `${filename}.downloading`);
const downloadLocation = _path.default.resolve(_this3.downloadDir, filename);
const tempDownloadLocation = _path.default.resolve(_this3.downloadDir, `${filename}.downloading`);
console.log(`Downloading${proxy ? ` via proxy ${proxy}` : ''}:`, downloadUrl);

@@ -175,28 +184,28 @@ const downloadedFile = yield _this3.httpDownload(downloadOptions, downloadLocation, tempDownloadLocation);

const binaryName = _this4.platform === 'win32' ? 'mongod.exe' : 'mongod';
const extractDir = _path2.default.resolve(_this4.downloadDir, _this4.version);
const extractDir = _path.default.resolve(_this4.downloadDir, _this4.version);
_this4.debug(`extract(): ${extractDir}`);
if (!_fs2.default.existsSync(extractDir)) {
_fs2.default.mkdirSync(extractDir);
if (!_fs.default.existsSync(extractDir)) {
_fs.default.mkdirSync(extractDir);
}
let filter;
if (_this4.platform === 'win32') {
filter = function filter(file) {
return (/bin\/mongod.exe$/.test(file.path) || /.dll$/.test(file.path)
);
filter = file => {
return /bin\/mongod.exe$/.test(file.path) || /.dll$/.test(file.path);
};
} else {
filter = function filter(file) {
return (/bin\/mongod$/.test(file.path)
);
};
filter = file => /bin\/mongod$/.test(file.path);
}
yield (0, _decompress2.default)(mongoDBArchive, extractDir, {
yield (0, _decompress.default)(mongoDBArchive, extractDir, {
// extract only `bin/mongod` file
filter,
// extract to root folder
map: function map(file) {
file.path = _path2.default.basename(file.path); // eslint-disable-line
map: file => {
file.path = _path.default.basename(file.path); // eslint-disable-line
return file;

@@ -206,5 +215,6 @@ }

if (!_this4.locationExists(_path2.default.resolve(_this4.downloadDir, _this4.version, binaryName))) {
if (!_this4.locationExists(_path.default.resolve(_this4.downloadDir, _this4.version, binaryName))) {
throw new Error(`MongoBinaryDownload: missing mongod binary in ${mongoDBArchive}`);
}
return extractDir;

@@ -218,25 +228,25 @@ })();

return _asyncToGenerator(function* () {
return new Promise(function (resolve, reject) {
const fileStream = _fs2.default.createWriteStream(tempDownloadLocation);
return new Promise((resolve, reject) => {
const fileStream = _fs.default.createWriteStream(tempDownloadLocation);
const req = _https2.default.get(httpOptions, function (response) {
const req = _https.default.get(httpOptions, response => {
_this5.dlProgress.current = 0;
_this5.dlProgress.length = parseInt(response.headers['content-length'], 10);
_this5.dlProgress.totalMb = Math.round(_this5.dlProgress.length / 1048576 * 10) / 10;
response.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
fileStream.on('finish', function () {
fileStream.close();
_fs2.default.renameSync(tempDownloadLocation, downloadLocation);
_fs.default.renameSync(tempDownloadLocation, downloadLocation);
_this5.debug(`renamed ${tempDownloadLocation} to ${downloadLocation}`);
resolve(downloadLocation);
});
response.on('data', function (chunk) {
response.on('data', chunk => {
_this5.printDownloadProgress(chunk);
});
req.on('error', e => {
_this5.debug('request error:', e);
req.on('error', function (e) {
_this5.debug('request error:', e);
reject(e);

@@ -251,10 +261,7 @@ });

this.dlProgress.current += chunk.length;
const now = Date.now();
if (now - this.dlProgress.lastPrintedAt < 2000) return;
this.dlProgress.lastPrintedAt = now;
const percentComplete = Math.round(100.0 * this.dlProgress.current / this.dlProgress.length * 10) / 10;
const mbComplete = Math.round(this.dlProgress.current / 1048576 * 10) / 10;
const crReturn = this.platform === 'win32' ? '\x1b[0G' : '\r';

@@ -266,3 +273,4 @@ process.stdout.write(`Downloading MongoDB ${this.version}: ${percentComplete} % (${mbComplete}mb ` + `/ ${this.dlProgress.totalMb}mb)${crReturn}`);

try {
_fs2.default.lstatSync(location);
_fs.default.lstatSync(location);
return true;

@@ -274,3 +282,5 @@ } catch (e) {

}
}
exports.default = MongoBinaryDownload;

@@ -1,2 +0,2 @@

'use strict';
"use strict";

@@ -6,17 +6,37 @@ Object.defineProperty(exports, "__esModule", {

});
exports.default = void 0;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _getos = _interopRequireDefault(require("getos"));
var _getos = require('getos');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _getos2 = _interopRequireDefault(_getos);
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/* eslint-disable class-methods-use-this */
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
class MongoBinaryDownloadUrl {
constructor({
platform,
arch,
version,
os
}) {
_defineProperty(this, "platform", void 0);
constructor({ platform, arch, version, os }) {
_defineProperty(this, "arch", void 0);
_defineProperty(this, "version", void 0);
_defineProperty(this, "os", void 0);
this.platform = this.translatePlatform(platform);

@@ -44,4 +64,6 @@ this.arch = this.translateArch(arch, this.platform);

return _this2.getArchiveNameOsx();
case 'win32':
return _this2.getArchiveNameWin();
case 'linux':

@@ -52,5 +74,5 @@ default:

})();
}
} // https://www.mongodb.org/dl/win32
// https://www.mongodb.org/dl/win32
getArchiveNameWin() {

@@ -66,5 +88,5 @@ var _this3 = this;

})();
}
} // https://www.mongodb.org/dl/osx
// https://www.mongodb.org/dl/osx
getArchiveNameOsx() {

@@ -75,5 +97,7 @@ var _this4 = this;

let name = `mongodb-osx`;
if (!(_this4.version.indexOf('3.0') === 0 || _this4.version.indexOf('2.') === 0 || _this4.version.indexOf('1.') === 0)) {
name += '-ssl';
}
name += `-${_this4.arch}`;

@@ -83,5 +107,5 @@ name += `-${_this4.version}.tgz`;

})();
}
} // https://www.mongodb.org/dl/linux
// https://www.mongodb.org/dl/linux
getArchiveNameLinux() {

@@ -93,4 +117,4 @@ var _this5 = this;

name += `-${_this5.arch}`;
let osString;
let osString;
if (_this5.arch !== 'i686') {

@@ -100,2 +124,3 @@ if (!_this5.os) _this5.os = yield _this5.getos();

}
if (osString) {

@@ -106,3 +131,2 @@ name += `-${osString}`;

name += `-${_this5.version}.tgz`;
return name;

@@ -114,4 +138,4 @@ })();

return _asyncToGenerator(function* () {
return new Promise(function (resolve, reject) {
(0, _getos2.default)(function (e, os) {
return new Promise((resolve, reject) => {
(0, _getos.default)((e, os) => {
if (e) reject(e);

@@ -140,2 +164,3 @@ resolve(os);

}
console.warn(`Unknown linux distro ${os.dist}, falling back to legacy MongoDB build`);

@@ -148,2 +173,3 @@ return this.getLegacyVersionString(os);

const release = parseFloat(os.release);
if (release >= 9) {

@@ -156,2 +182,3 @@ name += '92';

}
return name;

@@ -163,2 +190,3 @@ }

const fedoraVer = parseInt(os.release, 10);
if (fedoraVer > 18) {

@@ -171,2 +199,3 @@ name += '70';

}
return name;

@@ -188,17 +217,18 @@ }

}
return name;
}
} // eslint-disable-next-line no-unused-vars
// eslint-disable-next-line no-unused-vars
getElementaryOSVersionString(os) {
return 'ubuntu1404';
}
} // eslint-disable-next-line no-unused-vars
// eslint-disable-next-line no-unused-vars
getMintVersionString(os) {
// unfortunately getos doesn't return version for Mint
return 'ubuntu1404';
}
} // eslint-disable-next-line no-unused-vars
// eslint-disable-next-line no-unused-vars
getLegacyVersionString(os) {

@@ -209,11 +239,10 @@ return '';

getSuseVersionString(os) {
var _ref = os.release.match(/(^11|^12)/) || [null],
_ref2 = _slicedToArray(_ref, 1);
const _ref = os.release.match(/(^11|^12)/) || [null],
_ref2 = _slicedToArray(_ref, 1),
release = _ref2[0];
const release = _ref2[0];
if (release) {
return `suse${release}`;
}
return '';

@@ -225,4 +254,3 @@ }

const ubuntuVer = os.release ? os.release.split('.') : [];
const majorVer = parseInt(ubuntuVer[0], 10);
// const minorVer: string = ubuntuVer[1];
const majorVer = parseInt(ubuntuVer[0], 10); // const minorVer: string = ubuntuVer[1];

@@ -244,2 +272,3 @@ if (os.release === '12.04') {

}
return name;

@@ -252,10 +281,15 @@ }

return 'osx';
case 'win32':
return 'win32';
case 'linux':
return 'linux';
case 'elementary OS':
return 'linux';
case 'sunos':
return 'sunos5';
default:

@@ -273,2 +307,3 @@ throw new Error(`unsupported OS ${platform}`);

}
throw new Error('unsupported architecture');

@@ -281,3 +316,5 @@ } else if (arch === 'x64') {

}
}
exports.default = MongoBinaryDownloadUrl;

@@ -1,2 +0,2 @@

'use strict';
"use strict";

@@ -6,20 +6,19 @@ Object.defineProperty(exports, "__esModule", {

});
exports.default = void 0;
var _child_process = require('child_process');
var _child_process = require("child_process");
var _path = require('path');
var _path = _interopRequireDefault(require("path"));
var _path2 = _interopRequireDefault(_path);
var _MongoBinary = _interopRequireDefault(require("./MongoBinary"));
var _MongoBinary = require('./MongoBinary');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _MongoBinary2 = _interopRequireDefault(_MongoBinary);
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/* eslint-disable class-methods-use-this */
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
class MongodbInstance {
static run(opts) {

@@ -31,2 +30,14 @@ const instance = new this(opts);

constructor(opts) {
_defineProperty(this, "opts", void 0);
_defineProperty(this, "debug", void 0);
_defineProperty(this, "childProcess", void 0);
_defineProperty(this, "killerProcess", void 0);
_defineProperty(this, "instanceReady", void 0);
_defineProperty(this, "instanceFailed", void 0);
this.opts = opts;

@@ -53,9 +64,7 @@

prepareCommandArgs() {
var _opts$instance = this.opts.instance;
const ip = _opts$instance.ip,
port = _opts$instance.port,
storageEngine = _opts$instance.storageEngine,
dbPath = _opts$instance.dbPath;
const _this$opts$instance = this.opts.instance,
ip = _this$opts$instance.ip,
port = _this$opts$instance.port,
storageEngine = _this$opts$instance.storageEngine,
dbPath = _this$opts$instance.dbPath;
const result = [];

@@ -67,3 +76,2 @@ result.push('--bind_ip', ip || '127.0.0.1');

result.push('--noauth');
return result;

@@ -76,9 +84,12 @@ }

return _asyncToGenerator(function* () {
const launch = new Promise(function (resolve, reject) {
_this.instanceReady = function () {
const launch = new Promise((resolve, reject) => {
_this.instanceReady = () => {
_this.debug('MongodbInstance: is ready!');
resolve(_this.childProcess);
};
_this.instanceFailed = function (err) {
_this.instanceFailed = err => {
_this.debug(`MongodbInstance: is failed: ${err.toString()}`);
if (_this.killerProcess) _this.killerProcess.kill();

@@ -88,7 +99,5 @@ reject(err);

});
const mongoBin = yield _MongoBinary2.default.getPath(_this.opts.binary);
const mongoBin = yield _MongoBinary.default.getPath(_this.opts.binary);
_this.childProcess = _this._launchMongod(mongoBin);
_this.killerProcess = _this._launchKiller(process.pid, _this.childProcess.pid);
yield launch;

@@ -104,7 +113,9 @@ return _this;

if (_this2.childProcess && !_this2.childProcess.killed) {
yield new Promise(function (resolve) {
yield new Promise(resolve => {
_this2.childProcess.once(`exit`, resolve);
_this2.childProcess.kill();
});
}
return _this2;

@@ -126,3 +137,2 @@ })();

childProcess.on('error', this.errorHandler.bind(this));
return childProcess;

@@ -133,4 +143,5 @@ }

// spawn process which kills itself and mongo process if current process is dead
const killer = (0, _child_process.spawn)(process.argv[0], [_path2.default.resolve(__dirname, 'mongo_killer.js'), parentPid.toString(), childPid.toString()], { stdio: 'pipe' });
const killer = (0, _child_process.spawn)(process.argv[0], [_path.default.resolve(__dirname, 'mongo_killer.js'), parentPid.toString(), childPid.toString()], {
stdio: 'pipe'
});
return killer;

@@ -153,4 +164,4 @@ }

this.debug(`${message.toString()}`);
const log = message.toString();
const log = message.toString();
if (/waiting for connections on port/i.test(log)) {

@@ -170,4 +181,7 @@ this.instanceReady();

}
}
exports.default = MongodbInstance;
MongodbInstance.childProcessList = [];
_defineProperty(MongodbInstance, "childProcessList", []);
{
"name": "mongodb-memory-server",
"version": "2.1.0",
"version": "2.2.0",
"description": "In-memory MongoDB Server. Designed with testing in mind, the server will allow you to connect your favourite ODM or client library to the MongoDB Server and run integration tests isolated from each other.",

@@ -27,28 +27,31 @@ "main": "lib/index.js",

"devDependencies": {
"babel-cli": "^6.26.0",
"babel-eslint": "^8.2.6",
"babel-jest": "^23.4.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-flow-strip-types": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"@babel/cli": "^7.0.0",
"@babel/core": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.0.0",
"@babel/plugin-proposal-object-rest-spread": "^7.0.0",
"@babel/plugin-proposal-optional-chaining": "^7.0.0",
"@babel/plugin-transform-flow-strip-types": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-flow": "^7.0.0",
"babel-core": "^7.0.0-bridge.0",
"babel-eslint": "^9.0.0",
"babel-jest": "^23.6.0",
"cz-conventional-changelog": "^2.1.0",
"eslint": "^5.2.0",
"eslint-config-airbnb-base": "^13.0.0",
"eslint-config-prettier": "^2.9.0",
"eslint": "^5.5.0",
"eslint-config-airbnb-base": "^13.1.0",
"eslint-config-prettier": "^3.0.1",
"eslint-plugin-flowtype": "^2.50.0",
"eslint-plugin-import": "^2.12.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-prettier": "^2.6.2",
"flow-bin": "^0.77.0",
"jest": "^23.4.2",
"mongodb": "3.1.1",
"flow-bin": "^0.80.0",
"jest": "^23.6.0",
"mongodb": "3.1.4",
"npm-run-all": "^4.1.3",
"prettier": "^1.14.0",
"prettier": "^1.14.2",
"rimraf": "^2.6.2",
"semantic-release": "^15.9.3"
"semantic-release": "^15.9.15"
},
"dependencies": {
"babel-runtime": "^6.26.0",
"debug": "^3.1.0",
"@babel/runtime": "^7.0.0",
"debug": "^4.0.1",
"decompress": "^4.2.0",

@@ -55,0 +58,0 @@ "get-port": "^4.0.0",

@@ -67,3 +67,10 @@ # mongodb-memory-server

```
Also you can use the environment variables for configure installation process
```
MONGOMS_DOWNLOAD_DIR=/path/to/mongodb/binaries
MONGOMS_PLATFORM=linux
MONGOMS_ARCH=x64
MONGOMS_VERSION=3
MONGOMS_DEBUG=1 # also available case-insensitive values: "on" "yes" "true"
```
### Simple test with MongoClient

@@ -70,0 +77,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc