Skip to content

Commit 6865520

Browse files
hasezoeynodkz
authored andcommitted
fix: add TSDoc to MongoInstance; code refactoring (typegoose#261)
* - deprecate: disable an specific rule, instead of all - MongoMemoryServer: add tsdoc to interfaces - MongoMemoryServer: remove ":" from one debug line - MongoMemoryServer: combine multiple "data.*" into the data creation - MongoMemoryServer: adding "@deprecated" to "getConnectionString" (tsdoc deprecate) * - types: add "ErrorVoidCallback" and "EmptyVoidCallback" - MongoInstance: add TSDoc - MongoInstance: fix some types - MongoInstance: change some variable names to better represent what they are for * Warn if debug is disabled, and still throw the error * remove nullish coalescing in places where it shouldnt be * Fix tests mock "console.warn" to not print expected warns to the console * move "getUriBase" to db_util (because it dosnt use any class-specific properties add interface "StartupInstanceData" make _startUpInstance's data variable not "any" anymore
1 parent bfc38a9 commit 6865520

File tree

7 files changed

+147
-87
lines changed

7 files changed

+147
-87
lines changed

packages/mongodb-memory-server-core/src/MongoMemoryServer.ts

Lines changed: 51 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
11
import { ChildProcess } from 'child_process';
22
import tmp from 'tmp';
33
import getPort from 'get-port';
4-
import { generateDbName } from './util/db_util';
4+
import { generateDbName, getUriBase } from './util/db_util';
55
import MongoInstance from './util/MongoInstance';
66
import { MongoBinaryOpts } from './util/MongoBinary';
7-
import {
8-
CallbackFn,
9-
DebugFn,
10-
MongoMemoryInstancePropT,
11-
StorageEngineT,
12-
SpawnOptions,
13-
} from './types';
14-
import { DirResult } from 'tmp';
7+
import { DebugFn, MongoMemoryInstancePropT, StorageEngineT, SpawnOptions } from './types';
158
import { isNullOrUndefined } from 'util';
169

1710
tmp.setGracefulCleanup();
1811

12+
/**
13+
* Starting Options
14+
*/
1915
export interface MongoMemoryServerOptsT {
2016
instance?: MongoMemoryInstancePropT;
2117
binary?: MongoBinaryOpts;
@@ -24,20 +20,28 @@ export interface MongoMemoryServerOptsT {
2420
autoStart?: boolean;
2521
}
2622

27-
export interface MongoInstanceDataT {
23+
/**
24+
* Data used by _startUpInstance's "data" variable
25+
*/
26+
export interface StartupInstanceData {
2827
port: number;
29-
dbPath: string;
28+
dbPath?: string;
3029
dbName: string;
3130
ip: string;
32-
uri: string;
31+
uri?: string;
3332
storageEngine: StorageEngineT;
34-
instance: MongoInstance;
35-
childProcess: ChildProcess;
36-
tmpDir?: {
37-
name: string;
38-
removeCallback: CallbackFn;
39-
};
4033
replSet?: string;
34+
tmpDir?: tmp.DirResult;
35+
}
36+
37+
/**
38+
* Information about the currently running instance
39+
*/
40+
export interface MongoInstanceDataT extends StartupInstanceData {
41+
dbPath: string; // re-declare, because in this interface it is *not* optional
42+
uri: string; // same as above
43+
instance: MongoInstance;
44+
childProcess?: ChildProcess;
4145
}
4246

4347
export default class MongoMemoryServer {
@@ -88,7 +92,7 @@ export default class MongoMemoryServer {
8892
* (when options.autoStart is true, this already got called)
8993
*/
9094
async start(): Promise<boolean> {
91-
this.debug('Called MongoMemoryServer.start() method:');
95+
this.debug('Called MongoMemoryServer.start() method');
9296
if (this.runningInstance) {
9397
throw new Error(
9498
'MongoDB instance already in status startup/running/error. Use opts.debug = true for more info.'
@@ -108,10 +112,7 @@ export default class MongoMemoryServer {
108112
})
109113
.catch((err) => {
110114
if (!this.opts.debug) {
111-
throw new Error(
112-
`${err.message}\n\nUse debug option for more info: ` +
113-
`new MongoMemoryServer({ debug: true })`
114-
);
115+
console.warn('Starting the instance failed, please enable "debug" for more infomation');
115116
}
116117
throw err;
117118
});
@@ -127,26 +128,26 @@ export default class MongoMemoryServer {
127128
* @private
128129
*/
129130
async _startUpInstance(): Promise<MongoInstanceDataT> {
130-
const data: any = {};
131-
let tmpDir: DirResult;
132-
133-
const instOpts = this.opts.instance || {};
134-
data.port = await getPort({ port: instOpts.port || undefined });
135-
data.dbName = generateDbName(instOpts.dbName);
136-
data.ip = instOpts.ip || '127.0.0.1';
137-
data.uri = await this._getUriBase(data.ip, data.port, data.dbName);
138-
data.storageEngine = instOpts.storageEngine || 'ephemeralForTest';
139-
data.replSet = instOpts.replSet;
140-
if (instOpts.dbPath) {
141-
data.dbPath = instOpts.dbPath;
142-
} else {
143-
tmpDir = tmp.dirSync({
131+
/** Shortcut to this.opts.instance */
132+
const instOpts = this.opts.instance ?? {};
133+
const data: StartupInstanceData = {
134+
port: await getPort({ port: instOpts.port ?? undefined }), // do (null or undefined) to undefined
135+
dbName: generateDbName(instOpts.dbName),
136+
ip: instOpts.ip ?? '127.0.0.1',
137+
storageEngine: instOpts.storageEngine ?? 'ephemeralForTest',
138+
replSet: instOpts.replSet,
139+
dbPath: instOpts.dbPath,
140+
tmpDir: undefined,
141+
};
142+
143+
data.uri = await getUriBase(data.ip, data.port, data.dbName);
144+
if (!data.dbPath) {
145+
data.tmpDir = tmp.dirSync({
144146
mode: 0o755,
145147
prefix: 'mongo-mem-',
146148
unsafeCleanup: true,
147149
});
148-
data.dbPath = tmpDir.name;
149-
data.tmpDir = tmpDir;
150+
data.dbPath = data.tmpDir.name;
150151
}
151152

152153
this.debug(`Starting MongoDB instance with following options: ${JSON.stringify(data)}`);
@@ -168,10 +169,14 @@ export default class MongoMemoryServer {
168169
spawn: this.opts.spawn,
169170
debug: this.debug,
170171
});
171-
data.instance = instance;
172-
data.childProcess = instance.childProcess;
173172

174-
return data;
173+
return {
174+
...data,
175+
dbPath: data.dbPath as string, // because otherwise the types would be incompatible
176+
uri: data.uri as string, // same as above
177+
instance: instance,
178+
childProcess: instance.childProcess ?? undefined, // convert null | undefined to undefined
179+
};
175180
}
176181

177182
/**
@@ -182,6 +187,7 @@ export default class MongoMemoryServer {
182187

183188
// just return "true" if the instance is already running / defined
184189
if (isNullOrUndefined(this.runningInstance)) {
190+
this.debug('Instance is already stopped, returning true');
185191
return true;
186192
}
187193

@@ -230,14 +236,6 @@ export default class MongoMemoryServer {
230236
}
231237
}
232238

233-
/**
234-
* Basic MongoDB Connection string
235-
* @private
236-
*/
237-
_getUriBase(host: string, port: number, dbName: string) {
238-
return `mongodb://${host}:${port}/${dbName}?`;
239-
}
240-
241239
/**
242240
* Get a mongodb-URI for a different DataBase
243241
* @param otherDbName Set this to "true" to generate a random DataBase name, otherwise a string to specify a DataBase name
@@ -249,10 +247,10 @@ export default class MongoMemoryServer {
249247
if (otherDbName) {
250248
if (typeof otherDbName === 'string') {
251249
// generate uri with provided DB name on existed DB instance
252-
return this._getUriBase(ip, port, otherDbName);
250+
return getUriBase(ip, port, otherDbName);
253251
}
254252
// generate new random db name
255-
return this._getUriBase(ip, port, generateDbName());
253+
return getUriBase(ip, port, generateDbName());
256254
}
257255

258256
return uri;
@@ -261,6 +259,7 @@ export default class MongoMemoryServer {
261259
/**
262260
* Get a mongodb-URI for a different DataBase
263261
* @param otherDbName Set this to "true" to generate a random DataBase name, otherwise a string to specify a DataBase name
262+
* @deprecated
264263
*/
265264
async getConnectionString(otherDbName: string | boolean = false): Promise<string> {
266265
// should this function be marked deprecated? because it is just a pass-through to getUri

packages/mongodb-memory-server-core/src/__tests__/MongoMemoryServer-test.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ describe('MongoMemoryServer', () => {
4747
.fn()
4848
.mockRejectedValueOnce(new Error('unknown error'));
4949

50+
console.warn = jest.fn(); // mock it to prevent writing to console
51+
5052
const mongoServer = new MongoMemoryServer({
5153
autoStart: false,
5254
instance: {
@@ -56,10 +58,8 @@ describe('MongoMemoryServer', () => {
5658

5759
expect(MongoMemoryServer.prototype._startUpInstance).toHaveBeenCalledTimes(0);
5860

59-
await expect(mongoServer.start()).rejects.toThrow(
60-
`unknown error\n\nUse debug option for more info: ` +
61-
`new MongoMemoryServer({ debug: true })`
62-
);
61+
await expect(mongoServer.start()).rejects.toThrow('unknown error');
62+
expect(console.warn).toHaveBeenCalled();
6363

6464
expect(MongoMemoryServer.prototype._startUpInstance).toHaveBeenCalledTimes(1);
6565
});

packages/mongodb-memory-server-core/src/types.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,6 @@ export interface ReplStatusReplT {
3737
export interface ReplStatusResultT {
3838
repl: ReplStatusReplT;
3939
}
40+
41+
export type ErrorVoidCallback = (err: any) => void;
42+
export type EmptyVoidCallback = () => void;

0 commit comments

Comments
 (0)