Socket
Socket
Sign inDemoInstall

mongodb-memory-server-core

Package Overview
Dependencies
Maintainers
1
Versions
270
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mongodb-memory-server-core - npm Package Compare versions

Comparing version 6.2.1 to 6.2.2

11

CHANGELOG.md

@@ -6,2 +6,13 @@ # Change Log

## [6.2.2](https://github.com/nodkz/mongodb-memory-server/compare/v6.2.1...v6.2.2) (2020-01-15)
### Bug Fixes
* add TSDoc to MongoInstance; code refactoring ([#261](https://github.com/nodkz/mongodb-memory-server/issues/261)) ([6865520](https://github.com/nodkz/mongodb-memory-server/commit/6865520))
## [6.2.1](https://github.com/nodkz/mongodb-memory-server/compare/v6.2.0...v6.2.1) (2019-12-30)

@@ -8,0 +19,0 @@

5

lib/__tests__/MongoMemoryServer-test.js

@@ -95,2 +95,3 @@ "use strict";

.mockRejectedValueOnce(new Error('unknown error'));
console.warn = jest.fn(); // mock it to prevent writing to console
mongoServer = new MongoMemoryServer({

@@ -103,6 +104,6 @@ autoStart: false,

expect(MongoMemoryServer.prototype._startUpInstance).toHaveBeenCalledTimes(0);
return [4 /*yield*/, expect(mongoServer.start()).rejects.toThrow("unknown error\n\nUse debug option for more info: " +
"new MongoMemoryServer({ debug: true })")];
return [4 /*yield*/, expect(mongoServer.start()).rejects.toThrow('unknown error')];
case 1:
_a.sent();
expect(console.warn).toHaveBeenCalled();
expect(MongoMemoryServer.prototype._startUpInstance).toHaveBeenCalledTimes(1);

@@ -109,0 +110,0 @@ return [2 /*return*/];

37

lib/MongoMemoryServer.d.ts
/// <reference types="node" />
import { ChildProcess } from 'child_process';
import tmp from 'tmp';
import MongoInstance from './util/MongoInstance';
import { MongoBinaryOpts } from './util/MongoBinary';
import { CallbackFn, DebugFn, MongoMemoryInstancePropT, StorageEngineT, SpawnOptions } from './types';
import { DebugFn, MongoMemoryInstancePropT, StorageEngineT, SpawnOptions } from './types';
/**
* Starting Options
*/
export interface MongoMemoryServerOptsT {

@@ -13,17 +17,24 @@ instance?: MongoMemoryInstancePropT;

}
export interface MongoInstanceDataT {
/**
* Data used by _startUpInstance's "data" variable
*/
export interface StartupInstanceData {
port: number;
dbPath: string;
dbPath?: string;
dbName: string;
ip: string;
uri: string;
uri?: string;
storageEngine: StorageEngineT;
instance: MongoInstance;
childProcess: ChildProcess;
tmpDir?: {
name: string;
removeCallback: CallbackFn;
};
replSet?: string;
tmpDir?: tmp.DirResult;
}
/**
* Information about the currently running instance
*/
export interface MongoInstanceDataT extends StartupInstanceData {
dbPath: string;
uri: string;
instance: MongoInstance;
childProcess?: ChildProcess;
}
export default class MongoMemoryServer {

@@ -70,7 +81,2 @@ runningInstance: Promise<MongoInstanceDataT> | null;

/**
* Basic MongoDB Connection string
* @private
*/
_getUriBase(host: string, port: number, dbName: string): string;
/**
* Get a mongodb-URI for a different DataBase

@@ -83,2 +89,3 @@ * @param otherDbName Set this to "true" to generate a random DataBase name, otherwise a string to specify a DataBase name

* @param otherDbName Set this to "true" to generate a random DataBase name, otherwise a string to specify a DataBase name
* @deprecated
*/

@@ -85,0 +92,0 @@ getConnectionString(otherDbName?: string | boolean): Promise<string>;

@@ -112,3 +112,3 @@ "use strict";

return __generator(this, function (_a) {
this.debug('Called MongoMemoryServer.start() method:');
this.debug('Called MongoMemoryServer.start() method');
if (this.runningInstance) {

@@ -130,4 +130,3 @@ throw new Error('MongoDB instance already in status startup/running/error. Use opts.debug = true for more info.');

if (!_this.opts.debug) {
throw new Error(err.message + "\n\nUse debug option for more info: " +
"new MongoMemoryServer({ debug: true })");
console.warn('Starting the instance failed, please enable "debug" for more infomation');
}

@@ -148,26 +147,26 @@ throw err;

MongoMemoryServer.prototype._startUpInstance = function () {
var _a, _b, _c, _d, _e;
return __awaiter(this, void 0, void 0, function () {
var data, tmpDir, instOpts, _a, _b, instance;
return __generator(this, function (_c) {
switch (_c.label) {
var instOpts, data, _f, _g, instance;
return __generator(this, function (_h) {
switch (_h.label) {
case 0:
data = {};
instOpts = this.opts.instance || {};
_a = data;
return [4 /*yield*/, get_port_1.default({ port: instOpts.port || undefined })];
instOpts = (_a = this.opts.instance, (_a !== null && _a !== void 0 ? _a : {}));
_f = {};
return [4 /*yield*/, get_port_1.default({ port: (_b = instOpts.port, (_b !== null && _b !== void 0 ? _b : undefined)) })];
case 1:
_a.port = _c.sent();
data.dbName = db_util_1.generateDbName(instOpts.dbName);
data.ip = instOpts.ip || '127.0.0.1';
_b = data;
return [4 /*yield*/, this._getUriBase(data.ip, data.port, data.dbName)];
data = (_f.port = _h.sent(),
_f.dbName = db_util_1.generateDbName(instOpts.dbName),
_f.ip = (_c = instOpts.ip, (_c !== null && _c !== void 0 ? _c : '127.0.0.1')),
_f.storageEngine = (_d = instOpts.storageEngine, (_d !== null && _d !== void 0 ? _d : 'ephemeralForTest')),
_f.replSet = instOpts.replSet,
_f.dbPath = instOpts.dbPath,
_f.tmpDir = undefined,
_f);
_g = data;
return [4 /*yield*/, db_util_1.getUriBase(data.ip, data.port, data.dbName)];
case 2:
_b.uri = _c.sent();
data.storageEngine = instOpts.storageEngine || 'ephemeralForTest';
data.replSet = instOpts.replSet;
if (instOpts.dbPath) {
data.dbPath = instOpts.dbPath;
}
else {
tmpDir = tmp_1.default.dirSync({
_g.uri = _h.sent();
if (!data.dbPath) {
data.tmpDir = tmp_1.default.dirSync({
mode: 493,

@@ -177,4 +176,3 @@ prefix: 'mongo-mem-',

});
data.dbPath = tmpDir.name;
data.tmpDir = tmpDir;
data.dbPath = data.tmpDir.name;
}

@@ -198,6 +196,4 @@ this.debug("Starting MongoDB instance with following options: " + JSON.stringify(data));

case 3:
instance = _c.sent();
data.instance = instance;
data.childProcess = instance.childProcess;
return [2 /*return*/, data];
instance = _h.sent();
return [2 /*return*/, __assign(__assign({}, data), { dbPath: data.dbPath, uri: data.uri, instance: instance, childProcess: (_e = instance.childProcess, (_e !== null && _e !== void 0 ? _e : undefined)) })];
}

@@ -219,2 +215,3 @@ });

if (util_1.isNullOrUndefined(this.runningInstance)) {
this.debug('Instance is already stopped, returning true');
return [2 /*return*/, true];

@@ -275,9 +272,2 @@ }

/**
* Basic MongoDB Connection string
* @private
*/
MongoMemoryServer.prototype._getUriBase = function (host, port, dbName) {
return "mongodb://" + host + ":" + port + "/" + dbName + "?";
};
/**
* Get a mongodb-URI for a different DataBase

@@ -299,6 +289,6 @@ * @param otherDbName Set this to "true" to generate a random DataBase name, otherwise a string to specify a DataBase name

// generate uri with provided DB name on existed DB instance
return [2 /*return*/, this._getUriBase(ip, port, otherDbName)];
return [2 /*return*/, db_util_1.getUriBase(ip, port, otherDbName)];
}
// generate new random db name
return [2 /*return*/, this._getUriBase(ip, port, db_util_1.generateDbName())];
return [2 /*return*/, db_util_1.getUriBase(ip, port, db_util_1.generateDbName())];
}

@@ -313,2 +303,3 @@ return [2 /*return*/, uri];

* @param otherDbName Set this to "true" to generate a random DataBase name, otherwise a string to specify a DataBase name
* @deprecated
*/

@@ -315,0 +306,0 @@ MongoMemoryServer.prototype.getConnectionString = function (otherDbName) {

@@ -32,2 +32,4 @@ export declare type DebugFn = (...args: any[]) => any;

}
export declare type ErrorVoidCallback = (err: any) => void;
export declare type EmptyVoidCallback = () => void;
//# sourceMappingURL=types.d.ts.map

@@ -188,2 +188,3 @@ "use strict";

case 0:
console.warn = jest.fn(); // mock it to prevent writing to console
du = new MongoBinaryDownloadUrl_1.default({

@@ -203,2 +204,3 @@ platform: 'linux',

_a.apply(void 0, [_b.sent()]).toBe('https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.6.3.tgz');
expect(console.warn.mock.calls.length).toEqual(2);
return [2 /*return*/];

@@ -205,0 +207,0 @@ }

@@ -11,3 +11,7 @@ /**

export declare function getHost(uri: string): string;
/**
* Basic MongoDB Connection string
*/
export declare function getUriBase(host: string, port: number, dbName: string): string;
export default generateDbName;
//# sourceMappingURL=db_util.d.ts.map

@@ -23,3 +23,10 @@ "use strict";

exports.getHost = getHost;
/**
* Basic MongoDB Connection string
*/
function getUriBase(host, port, dbName) {
return "mongodb://" + host + ":" + port + "/" + dbName + "?";
}
exports.getUriBase = getUriBase;
exports.default = generateDbName;
//# sourceMappingURL=db_util.js.map

@@ -11,3 +11,3 @@ "use strict";

}
// eslint-disable-next-line
// eslint-disable-next-line no-console
console.log("[mongodb-memory-server]: DEPRECATION MESSAGE: " + msg + " " + stackStr + "\n\n");

@@ -14,0 +14,0 @@ }

/// <reference types="node" />
import { ChildProcess } from 'child_process';
import { MongoBinaryOpts } from './MongoBinary';
import { DebugPropT, StorageEngineT, SpawnOptions } from '../types';
import { DebugPropT, StorageEngineT, SpawnOptions, DebugFn, ErrorVoidCallback, EmptyVoidCallback } from '../types';
export interface MongodOps {

@@ -20,6 +20,9 @@ instance: {

}
/**
* MongoDB Instance Handler Class
*/
export default class MongoInstance {
static childProcessList: ChildProcess[];
opts: MongodOps;
debug: Function;
debug: DebugFn;
childProcess: ChildProcess | null;

@@ -30,18 +33,55 @@ killerProcess: ChildProcess | null;

isInstanceReady: boolean;
instanceReady: () => void;
instanceFailed: (err: any) => void;
instanceReady: EmptyVoidCallback;
instanceFailed: ErrorVoidCallback;
constructor(opts: MongodOps);
/**
* Create an new instance an call method "run"
* @param opts Options passed to the new instance
*/
static run(opts: MongodOps): Promise<MongoInstance>;
/**
* Create an array of arguments for the mongod instance
*/
prepareCommandArgs(): string[];
run(): Promise<MongoInstance>;
/**
* Create the mongod process
*/
run(): Promise<this>;
kill(): Promise<MongoInstance>;
/**
* Get the PID of the mongod instance
*/
getPid(): number | undefined;
/**
* Wait until the Primary mongod is running
*/
waitPrimaryReady(): Promise<boolean>;
/**
* Actually launch mongod
* @param mongoBin The binary to run
*/
_launchMongod(mongoBin: string): ChildProcess;
/**
* Spawn an child to kill the parent and the mongod instance if both are Dead
* @param parentPid Parent to kill
* @param childPid Mongod process to kill
*/
_launchKiller(parentPid: number, childPid: number): ChildProcess;
errorHandler(err: string): void;
/**
* Write the CLOSE event to the debug function
* @param code The Exit code
*/
closeHandler(code: number): void;
/**
* Write STDERR to debug function
* @param message The STDERR line to write
*/
stderrHandler(message: string | Buffer): void;
/**
* Write STDOUT to debug function AND instanceReady/instanceFailed if inputs match
* @param message The STDOUT line to write/parse
*/
stdoutHandler(message: string | Buffer): void;
}
//# sourceMappingURL=MongoInstance.d.ts.map

@@ -56,4 +56,8 @@ "use strict";

var MongoBinary_1 = __importDefault(require("./MongoBinary"));
/**
* MongoDB Instance Handler Class
*/
var MongoInstance = /** @class */ (function () {
function MongoInstance(opts) {
var _a;
this.isInstancePrimary = false;

@@ -90,3 +94,3 @@ this.isInstanceReady = false;

var debugFn = this.debug;
var port = this.opts.instance && this.opts.instance.port;
var port = (_a = this.opts.instance) === null || _a === void 0 ? void 0 : _a.port;
this.debug = function (msg) {

@@ -96,6 +100,18 @@ debugFn("Mongo[" + port + "]: " + msg);

}
/**
* Create an new instance an call method "run"
* @param opts Options passed to the new instance
*/
MongoInstance.run = function (opts) {
var instance = new this(opts);
return instance.run();
return __awaiter(this, void 0, void 0, function () {
var instance;
return __generator(this, function (_a) {
instance = new this(opts);
return [2 /*return*/, instance.run()];
});
});
};
/**
* Create an array of arguments for the mongod instance
*/
MongoInstance.prototype.prepareCommandArgs = function () {

@@ -117,4 +133,7 @@ var _a = this.opts.instance, ip = _a.ip, port = _a.port, storageEngine = _a.storageEngine, dbPath = _a.dbPath, replSet = _a.replSet, auth = _a.auth, args = _a.args;

result.push('--replSet', replSet);
return result.concat(args || []);
return result.concat((args !== null && args !== void 0 ? args : []));
};
/**
* Create the mongod process
*/
MongoInstance.prototype.run = function () {

@@ -200,5 +219,12 @@ return __awaiter(this, void 0, void 0, function () {

};
/**
* Get the PID of the mongod instance
*/
MongoInstance.prototype.getPid = function () {
return this.childProcess ? this.childProcess.pid : undefined;
var _a;
return (_a = this.childProcess) === null || _a === void 0 ? void 0 : _a.pid;
};
/**
* Wait until the Primary mongod is running
*/
MongoInstance.prototype.waitPrimaryReady = function () {

@@ -217,4 +243,9 @@ return __awaiter(this, void 0, void 0, function () {

};
/**
* Actually launch mongod
* @param mongoBin The binary to run
*/
MongoInstance.prototype._launchMongod = function (mongoBin) {
var spawnOpts = this.opts.spawn || {};
var _a;
var spawnOpts = (_a = this.opts.spawn, (_a !== null && _a !== void 0 ? _a : {}));
if (!spawnOpts.stdio)

@@ -233,2 +264,7 @@ spawnOpts.stdio = 'pipe';

};
/**
* Spawn an child to kill the parent and the mongod instance if both are Dead
* @param parentPid Parent to kill
* @param childPid Mongod process to kill
*/
MongoInstance.prototype._launchKiller = function (parentPid, childPid) {

@@ -243,4 +279,4 @@ var _this = this;

], { stdio: 'pipe' });
['exit', 'message', 'disconnect', 'error'].forEach(function (e) {
killer.on(e, function () {
['exit', 'message', 'disconnect', 'error'].forEach(function (type) {
killer.on(type, function () {
var args = [];

@@ -250,3 +286,3 @@ for (var _i = 0; _i < arguments.length; _i++) {

}
_this.debug("[MongoKiller]: " + e + " - " + JSON.stringify(args));
_this.debug("[MongoKiller]: " + type + " - " + JSON.stringify(args));
});

@@ -259,31 +295,43 @@ });

};
/**
* Write the CLOSE event to the debug function
* @param code The Exit code
*/
MongoInstance.prototype.closeHandler = function (code) {
this.debug("CLOSE: " + code);
};
/**
* Write STDERR to debug function
* @param message The STDERR line to write
*/
MongoInstance.prototype.stderrHandler = function (message) {
this.debug("STDERR: " + message.toString());
};
/**
* Write STDOUT to debug function AND instanceReady/instanceFailed if inputs match
* @param message The STDOUT line to write/parse
*/
MongoInstance.prototype.stdoutHandler = function (message) {
var _this = this;
this.debug("" + message.toString());
var log = message.toString();
if (/waiting for connections on port/i.test(log)) {
var line = message.toString();
this.debug("STDOUT: " + line);
if (/waiting for connections on port/i.test(line)) {
this.instanceReady();
}
else if (/addr already in use/i.test(log)) {
else if (/addr already in use/i.test(line)) {
this.instanceFailed("Port " + this.opts.instance.port + " already in use");
}
else if (/mongod instance already running/i.test(log)) {
else if (/mongod instance already running/i.test(line)) {
this.instanceFailed('Mongod already running');
}
else if (/permission denied/i.test(log)) {
else if (/permission denied/i.test(line)) {
this.instanceFailed('Mongod permission denied');
}
else if (/Data directory .*? not found/i.test(log)) {
else if (/Data directory .*? not found/i.test(line)) {
this.instanceFailed('Data directory not found');
}
else if (/CURL_OPENSSL_3.*not found/i.test(log)) {
this.instanceFailed('libcurl3 is not available on your system. Mongod requires it and cannot be started without it. You should manually install libcurl3 or try to use older Mongodb version eg. 3.6.12');
else if (/CURL_OPENSSL_3.*not found/i.test(line)) {
this.instanceFailed('libcurl3 is not available on your system. Mongod requires it and cannot be started without it.\n' +
'You should manually install libcurl3 or try to use an newer version of MongoDB\n');
}
else if (/shutting down with code/i.test(log)) {
else if (/shutting down with code/i.test(line)) {
// if mongod started succesfully then no error on shutdown!

@@ -294,11 +342,9 @@ if (!this.isInstanceReady) {

}
else if (/\*\*\*aborting after/i.test(log)) {
else if (/\*\*\*aborting after/i.test(line)) {
this.instanceFailed('Mongod internal error');
}
else if (/transition to primary complete; database writes are now permitted/.test(log)) {
else if (/transition to primary complete; database writes are now permitted/.test(line)) {
this.isInstancePrimary = true;
this.waitForPrimaryResolveFns.forEach(function (resolveFn) {
_this.debug('Calling waitForPrimary resolve function');
resolveFn(true);
});
this.debug('Calling all waitForPrimary resolve functions');
this.waitForPrimaryResolveFns.forEach(function (resolveFn) { return resolveFn(true); });
}

@@ -305,0 +351,0 @@ };

{
"name": "mongodb-memory-server-core",
"version": "6.2.1",
"version": "6.2.2",
"description": "MongoDB Server for testing (core package, without autodownload). The server will allow you to connect your favourite ODM or client library to the MongoDB Server and run parallel integration tests isolated from each other.",

@@ -78,3 +78,3 @@ "main": "lib/index",

},
"gitHead": "bfc38a9f8a87a2fdd720beed3ae5ebca238db9a4"
"gitHead": "1aa8c849dd0667d7e77bebe56ac3353c3657c3dc"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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