All files index.js

69.23% Statements 45/65
51.28% Branches 20/39
71.43% Functions 10/14
68.75% Lines 44/64
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              2x                                             3x 3x                   3x     3x 3x     3x         9x           3x           3x                                   3x       3x     3x 3x 3x 3x     3x 3x     3x   3x                   3x   3x 1x         3x 3x 3x   3x 3x   3x       3x   3x   3x     3x     3x 3x 3x     3x 3x       8x 8x               5x     5x                 5x       5x                          
/* @flow */
 
import { MongodHelper } from 'mongodb-prebuilt';
import uuid from 'uuid/v4';
import tmp from 'tmp';
import getport from 'get-port';
 
tmp.setGracefulCleanup();
 
export type MongoMemoryServerOptsT = {
  port?: ?number,
  storageEngine?: string,
  dbPath?: string,
  autoStart?: boolean,
  debug?: boolean,
};
 
export type MongoInstanceDataT = {
  port: number,
  dbPath: string,
  uri: string,
  storageEngine: string,
  mongodCli: MongodHelper,
  tmpDir?: {
    name: string,
    removeCallback: Function,
  },
};
 
async function generateConnectionString(port: number, dbName: ?string): Promise<string> {
  const db = dbName || (await uuid());
  return `mongodb://localhost:${port}/${db}`;
}
 
export default class MongoDBMemoryServer {
  static mongodHelperStartup: ?Promise<any>;
  isRunning: boolean = false;
  runningInstance: ?Promise<MongoInstanceDataT>;
  opts: MongoMemoryServerOptsT;
 
  constructor(opts?: MongoMemoryServerOptsT = {}) {
    this.opts = opts;
 
    // autoStart by default
    Eif (!opts.hasOwnProperty('autoStart') || opts.autoStart) {
      Iif (opts.debug) {
        console.log('Autostarting MongoDB instance...');
      }
      this.start();
    }
  }
 
  debug(msg: string) {
    Iif (this.opts.debug) {
      console.log(msg);
    }
  }
 
  async start(): Promise<boolean> {
    Iif (this.runningInstance) {
      throw new Error(
        'MongoDB instance already in status startup/running/error. Use opts.debug = true for more info.'
      );
    }
 
    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.port = null;
          return this._startUpInstance();
        }
        throw 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(() => true);
  }
 
  async _startUpInstance(): Promise<MongoInstanceDataT> {
    const data = {};
    let tmpDir;
 
    data.port = await getport(this.opts.port);
    data.uri = await generateConnectionString(data.port);
    data.storageEngine = this.opts.storageEngine || 'ephemeralForTest';
    Iif (this.opts.dbPath) {
      data.dbPath = this.opts.dbPath;
    } else {
      tmpDir = tmp.dirSync({ prefix: 'mongo-mem-', unsafeCleanup: true });
      data.dbPath = tmpDir.name;
    }
 
    this.debug(`Starting MongoDB instance with following options: ${JSON.stringify(data)}`);
 
    const mongodCli = new MongodHelper([
      '--port',
      data.port,
      '--storageEngine',
      data.storageEngine,
      '--dbpath',
      data.dbPath,
      '--noauth',
    ]);
 
    mongodCli.debug.enabled = this.opts.debug;
 
    if (this.constructor.mongodHelperStartup) {
      await this.constructor.mongodHelperStartup;
    }
 
    // Download if not exists mongo binaries in ~/.mongodb-prebuilt
    // After that startup MongoDB instance
    const startupPromise = mongodCli.run();
    this.constructor.mongodHelperStartup = startupPromise;
    await startupPromise;
 
    data.mongodCli = mongodCli;
    data.tmpDir = tmpDir;
 
    return data;
  }
 
  async stop(): Promise<boolean> {
    const { mongodCli, port, tmpDir } = (await this.getInstanceData(): MongoInstanceDataT);
 
    Eif (mongodCli && mongodCli.mongoBin.childProcess) {
      // .mongoBin.childProcess.connected
      this.debug(
        `Shutdown MongoDB server on port ${port} with pid ${mongodCli.mongoBin.childProcess.pid}`
      );
      mongodCli.mongoBin.childProcess.kill();
    }
 
    Eif (tmpDir) {
      this.debug(`Removing tmpDir ${tmpDir.name}`);
      tmpDir.removeCallback();
    }
 
    this.runningInstance = null;
    return true;
  }
 
  async getInstanceData(): Promise<MongoInstanceDataT> {
    Eif (this.runningInstance) {
      return this.runningInstance;
    }
    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.'
    );
  }
 
  async getUri(otherDbName?: string | boolean = false): Promise<string> {
    const { uri, port } = (await this.getInstanceData(): MongoInstanceDataT);
 
    // IF true OR string
    Iif (otherDbName) {
      if (typeof otherDbName === 'string') {
        // generate uri with provided DB name on existed DB instance
        return generateConnectionString(port, otherDbName);
      }
      // generate new random db name
      return generateConnectionString(port);
    }
 
    return uri;
  }
 
  async getConnectionString(otherDbName: string | boolean = false): Promise<string> {
    return this.getUri(otherDbName);
  }
 
  async getPort(): Promise<number> {
    const { port } = (await this.getInstanceData(): MongoInstanceDataT);
    return port;
  }
 
  async getDbPath(): Promise<string> {
    const { dbPath } = (await this.getInstanceData(): MongoInstanceDataT);
    return dbPath;
  }
}