All files / src index.js

100% Statements 29/29
88.89% Branches 8/9
100% Functions 9/9
100% Lines 29/29
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    1x                       34x 34x         34x     34x 34x 34x     34x 34x                           27x 27x 27x 1x 1x     26x 26x   26x   1x 1x                     29x 29x 3x 3x     26x 26x   26x   3x 3x             1x  
'use strict';
 
const express = require('express');
 
class Mockiji {
  /**
   * Constructor.
   *
   * @param {Object} options
   * @param {Object} options.configuration - A configuration object
   * @param {string} options.configFile - A path to a configuration file
   */
  constructor(options = {}) {
    // Create Configuration and Logger
    this.Configuration = require('./utils/Configuration')(options);
    this.Logger = require('./utils/Logger')({
      Configuration: this.Configuration
    });
 
    // Server
    this.app = express();
 
    // Server configuration
    this.app.use(express.json());
    this.app.use(express.urlencoded());
    this.http = require('http').Server(this.app);
 
    // Routes
    this.routes = require('./routes/index');
    this.routes({
      Configuration: this.Configuration,
      Logger: this.Logger,
      app: this.app
    });
  }
 
  /**
   * Start the server.
   *
   * @return {Promise}
   */
  start() {
    // Launch server
    const port = this.Configuration.get('port');
    return new Promise((resolve, reject) => {
      if (this.http && this.http.listening) {
        reject(new Error('Server is already listening'));
        return;
      }
 
      this.http.once('error', reject);
      this.http.listen(port, resolve);
    }).then(
      () => { this.Logger.info(`Server listening on port ${port}`); },
      (error) => {
        this.Logger.error(`Could not start server on port ${port}`);
        throw error;
      }
    );
  }
 
  /**
   * Stop the server.
   *
   * @return {Promise}
   */
  stop() {
    return new Promise((resolve, reject) => {
      if (!this.http || !this.http.listening) {
        reject(new Error('Server is not currently listening'));
        return;
      }
 
      this.http.once('error', reject);
      this.http.close(resolve);
    }).then(
      () => { this.Logger.info(`Server stopped listening`); },
      (error) => {
        this.Logger.error(`Could not stop server`);
        throw error;
      }
    )
  }
}
 
// Expose
module.exports = Mockiji;