All files / src/services FileLoaderService.js

90.51% Statements 124/137
86.36% Branches 38/44
94.44% Functions 17/18
90.51% Lines 124/137
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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300    1x 1x 1x 1x 1x 1x         1x                   64x 64x             67x   67x 67x 632x 343x     289x 289x 65x 65x 65x       67x 1x 1x     66x 62x 62x     4x             61x 61x 61x 61x 61x 61x   61x 61x 61x 61x   61x 2x 2x 1x       59x     61x 60x     61x     9x   9x 9x   9x 9x 9x 9x 9x     9x 1x   9x     9x                   52x       52x 51x 51x 49x   2x       2x 2x 2x       2x     1x 1x 1x         1x     61x               61x               9x 9x 9x   9x 9x                                           9x   9x                         61x   61x 61x 4x     61x             60x   60x 60x 60x     60x       61x 61x 2x   59x       1x 1x 1x 1x       1x 1x 1x       1x   1x 1x     1x 12x 12x 12x 12x 12x 12x 12x       1x       1x 1x 1x 1x 1x 1x 3x 3x 3x 3x               1x       1x  
'use strict';
 
const util = require('util');
const fs = require('fs');
const merge = require('merge');
const url = require('url');
const glob = require('glob-all');
const jsonfile = require('jsonfile');
 
/**
 * UTF8 Encoding
 */
const UTF8 = 'utf8';
 
/**
 * This service is for loading the right file
 */
class FileLoaderService {
  /**
   * Constructor.
   */
  constructor({Configuration, Logger}) {
    this.Configuration = Configuration;
    this.Logger = Logger;
  }
 
  /**
   * Find the right file to load
   */
  find(paths, unlimited) {
    let files = [];
 
    let fileMatch = false;
    paths.forEach((element) => {
      if (fileMatch && !unlimited) {
        return;
      }
 
      let candidateFile = glob.sync(element);
      if (candidateFile.length > 0) {
        this.Logger.debug({'files': files}, `Mock file found: ${candidateFile[0]}`);
        files.push(candidateFile[0]);
        fileMatch = true;
      }
    });
 
    if (unlimited) {
      this.Logger.debug({'files': files}, `${files.length} matching file(s) found, returning all of them`);
      return files;
    }
 
    if (files.length > 0) {
      this.Logger.debug({'files': files}, `${files.length} matching file(s) found, returning "${files[0]}"`);
      return files[0];
    }
 
    return null;
  }
 
  /**
   * Load the file located at the path
   */
  load(pPath, request, paths) {
    let fileContent = fs.readFileSync(pPath, 'utf8');
    let content = null;
    let notices = [];
    let path = null;
    let extension = null;
    let location = null;
 
    let isScriptMock = this._isScriptMockFilePath(pPath);
    let httpCode = this._extractHttpCodeFromFileName(pPath);
    let mockData = {};
    let delay = 1;
 
    if (isScriptMock) {
      path = this.find(paths.scripts);
      if (path !== null) {
        mockData = this._loadMockData(pPath, paths.mocks);
      }
    }
    else {
      path = pPath;
    }
 
    if (path !== null) {
      extension = this._extractExtensionFromFileName(path);
    }
 
    if (extension === 'js') {
 
      // Load the possible memory file
      let memory = this._loadMemoryFile(path);
 
      delete require.cache[require.resolve(path)];
      let jsMock = require(path);
 
      try {
        let response = new jsMock(this._buildMockRequestObject(request), mockData, memory);
        content = response.content;
        httpCode = response.httpCode || httpCode;
        Iif (response.hasOwnProperty('extension')) {
          extension = response.extension;
        }
        if (response.hasOwnProperty('location')) {
          location = response.location;
        }
        delay = response.delay || delay;
 
        // Save memory if returned
        Iif (response.memory) {
          this._updateMemoryFile(path, response.memory);
        }
 
      } catch (e) {
        const message = `The mock file is not valid (${path})`;
        content = { 'error': message, 'e': util.inspect(e, false, 2, true) };
        notices.push(message);
      }
    }
    else Iif (extension === 'html') {
      content = fileContent;
      httpCode = 200;
    }
    else if (extension !== null) {
      try {
        if (fileContent.length > 0) {
          content = JSON.parse(fileContent);
        } else {
          notices.push('The mock file is empty');
        }
      }
      catch (e) {
        httpCode = this.Configuration.get('http_codes.mock_file_invalid');
        const message = 'The mock file contains invalid JSON';
        content =  {
          'errorCode': httpCode,
          'errorDescription': message
        };
        notices.push(message);
      }
    } else {
      httpCode = this.Configuration.get('http_codes.mock_file_invalid');
      const message = `Mockiji loaded ${pPath} but could not find the actual script file.`;
      content =  {
        'errorCode': httpCode,
        'errorDescription': message,
        'evaluatedScriptFilePaths': paths.scripts
      };
      notices.push(message);
    }
 
    let data = {
      rawContent: content,
      extension,
      location,
      httpCode,
      delay,
      notices
    };
    return data;
  }
 
  /**
   * Check if the memory file fitting the mockPath exist and returns its content
   * @return object from the memory file or {} if the file does not exist
   */
  _loadMemoryFile(mockPath) {
    let memoryPath = mockPath.replace('.js','.memory.json');
    try {
      return jsonfile.readFileSync(memoryPath);
    } catch (e) {
      this.Logger.debug({'exception': e}, `Could not open memory file "${memoryPath}"`);
      return {};
    }
  }
 
  /**
   * Update (or create) the memory file fitting the mockPath with the memory content
   */
  _updateMemoryFile(mockPath, memory) {
    let memoryPath = mockPath.replace('.js','.memory.json');
    try {
      jsonfile.writeFileSync(memoryPath, memory, {spaces:2});
      this.Logger.info(`Wrote into memory file "${memoryPath}"`);
    } catch (e) {
      this.Logger.error({'exception': e}, `Could not write into memory file "${memoryPath}"`);
    }
  }
 
  /**
   * Build an object containing the method, url (pathname) and query (queryString) from the request
   * @return object the built object
   */
  _buildMockRequestObject(request) {
    let urlComponents = url.parse(request.url, true);
 
    return {
      'method': request.method,
      'body': request.body,
      'headers': request.headers,
      'url': urlComponents.pathname,
      'query': urlComponents.query
    }
  }
 
  /**
   * Extract the HTTP Code from the filename (just before the final extension)
   */
  _extractHttpCodeFromFileName(filename) {
    let httpCode = 200;
 
    let matches = filename.match(/\.([0-9]{3})\.[a-z0-9]+$/i);
    if (matches != null) {
      httpCode = matches[1];
    }
 
    return httpCode;
  }
 
  /**
   * Extract the file extension from the filename
   */
  _extractExtensionFromFileName(filename) {
    let extension = null;
 
    let matches = filename.match(/\.([a-z0-9]+)$/i);
    Eif (matches != null) {
      extension = matches[1];
    }
 
    return extension;
  }
 
  _isScriptMockFilePath(filename) {
    let matches = filename.match(/\.script$/i);
    if (matches != null) {
      return true;
    }
    return false;
  }
 
  _loadMockData(path, paths) {
    let dataFileNames = this._extractDataFileNamesFromScriptFile(path);
    let dataPaths = this._convertMockPathsToDataPaths(paths, dataFileNames);
    let data = this._loadMockDataFromDataPaths(dataPaths);
    return data;
  }
 
  _extractDataFileNamesFromScriptFile(path) {
    let fileContent = fs.readFileSync(path, UTF8);
    let paths = fileContent.trim().split(/\r?\n/);
    return paths;
  }
 
  _convertMockPathsToDataPaths(paths, files) {
    let dataPaths = {};
 
    files.forEach((file) => {
      dataPaths[file] = [];
    });
 
    paths.forEach((path) => {
      let lastSlashPosition = path.lastIndexOf('/');
      Eif (lastSlashPosition !== -1) {
        files.forEach((file) => {
          let dataDefaultPath = [path.substring(0, lastSlashPosition), '@default/@data', file].join('/');
          dataPaths[file].push(dataDefaultPath);
          let dataPath = [path.substring(0, lastSlashPosition), '@data', file].join('/');
          dataPaths[file].push(dataPath);
        })
      }
    });
    return dataPaths;
  }
 
  _loadMockDataFromDataPaths(dataPaths) {
    let data = {};
    for (let file in dataPaths) {
      let paths = dataPaths[file];
      let mockDataPaths = this.find(paths, true);
      Eif (mockDataPaths !== null) {
        mockDataPaths.reverse().forEach((mockDataPath) => {
          let fileContent = fs.readFileSync(mockDataPath, 'utf8');
          try {
            let jsonContent = JSON.parse(fileContent);
            data = merge.recursive(true, data, jsonContent);
          }
          catch (e) {
            this.Logger.error({'exception': e}, `Could not parse mock file "${mockDataPath}"`);
          }
        });
      }
    }
    return data;
  }
}
 
module.exports = FileLoaderService;