All files buildApiResponse.js

75.75% Statements 75/99
50.63% Branches 40/79
72.72% Functions 8/11
75.75% Lines 75/99

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2602x 2x 2x                   2x 6x             6x 7x   7x     2x   2x 1x     2x       2x   2x 1x     2x           1x 1x 1x   1x 1x 1x   1x 1x 1x       6x                     2x 6x     6x 4x           6x 1x           5x       2x 2x         1x 1x   1x 1x     1x 1x     5x                                 2x 1x               2x 2x 2x   2x 1x 1x 1x       1x             1x                   1x 1x   1x   1x                                                                   1x 1x   1x       1x             1x           2x                         2x 2x   2x 2x 2x   2x   2x 1x     2x 1x   1x       2x  
const { logger } = require('./logger');
const { exampleApiDocResponse } = require('./apidocParse');
const { memo } = require('./global');
 
/**
 * Parse custom mock settings.
 *
 * @param {object} params
 * @param {Array} params.settings
 * @returns {{forceStatus: (number|undefined), delay: (number|undefined), reload: (number|undefined),
 *     response: (number|undefined)}}
 */
const getCustomMockSettings = memo(({ settings = [] } = {}) => {
  const updatedSettings = {
    delay: undefined,
    forceStatus: undefined,
    response: undefined,
    reload: undefined
  };
 
  settings?.forEach(val => {
    const [key = '', value] = Object.entries(val)?.[0] || [];
 
    switch (key.toLowerCase()) {
      case 'delay':
      case 'delayresponse':
        updatedSettings.delay = Number.parseInt(value, 10);
 
        if (Number.isNaN(updatedSettings.delay)) {
          updatedSettings.delay = 1000;
        }
 
        break;
      case 'force':
      case 'forcestatus':
      case 'forcedstatus':
        updatedSettings.forceStatus = Number.parseInt(value, 10);
 
        if (Number.isNaN(updatedSettings.forceStatus)) {
          updatedSettings.forceStatus = 200;
        }
 
        break;
      case 'response':
        updatedSettings.response = 'response';
        break;
      case 'random':
      case 'randomresponse':
        updatedSettings.response = 'response';
        updatedSettings.reload = true;
        break;
      case 'randomsuccess':
        updatedSettings.response = 'success';
        updatedSettings.reload = true;
        break;
      case 'randomerror':
        updatedSettings.response = 'error';
        updatedSettings.reload = true;
        break;
    }
  });
 
  return updatedSettings;
});
 
/**
 * Return passed mock mime type and parsed content
 *
 * @param {object} params
 * @param {string} params.content
 * @param {string} params.type
 * @returns {{content: string, contentType: string}}
 */
const getContentAndType = memo(({ content = '', type: contentType } = {}) => {
  let updatedContent = content;
  let updatedType;
 
  if (/^HTTP/.test(content)) {
    updatedContent = content.split(/\n/).slice(1).join('\n');
  }
 
  /**
   * Ignore content types that already contain a `/`
   */
  if (contentType?.split('/').length > 1) {
    return {
      content: updatedContent,
      contentType
    };
  }
 
  switch (contentType) {
    case 'zip':
    case 'gzip':
    case 'json':
      updatedType = `application/${contentType}`;
      break;
    case 'xml':
    case 'html':
    case 'csv':
    case 'css':
      updatedType = `text/${contentType}`;
      break;
    case 'svg':
      updatedType = 'image/svg+xml';
      break;
    case 'txt':
    default:
      updatedType = 'text/plain';
      break;
  }
 
  return {
    content: updatedContent,
    contentType: updatedType
  };
});
 
/**
 * Aggregate possible responses, return an example based on available configuration.
 *
 * @param {object} params
 * @param {object} params.mockSettings
 * @param {Array} params.successExamples
 * @param {Array} params.errorExamples
 * @param {string} params.type
 * @param {string} params.url
 * @returns {{authExample: {content: *, type: *}, example: {content: *, type: *}}}
 */
const getExampleResponse = async ({ mockSettings, successExamples = [], errorExamples = [], type, url } = {}) =>
  exampleApiDocResponse({ mockSettings, successExamples, errorExamples, type, url });
 
/**
 * Build API response
 *
 * @param {Array} apiJson
 * @returns {{app:Array, routesLoaded: boolean}}
 */
const buildResponse = (apiJson = []) => {
  const appResponses = [];
  let routesLoaded = 0;
 
  apiJson.forEach(({ error = {}, header, success = {}, type, url, mock } = {}) => {
    try {
      const mockSettings = getCustomMockSettings({ settings: mock?.settings, url });
      const memoGetExampleResponse = memo(getExampleResponse, {
        cacheLimit: mockSettings?.reload ? 0 : 25
      });
 
      appResponses.push({
        type,
        url,
        callback: async (request, response) => {
          /**
           * Leverage memo caching using isParams, isQuery.
           */
          const { example: updatedExample, authExample: updatedAuthExample } = await memoGetExampleResponse({
            mockSettings,
            successExamples: success.examples,
            errorExamples: error.examples,
            type,
            url,
            isParams: request?.params,
            isQuery: request?.query
          });
 
          const httpStatus = updatedExample?.status > 0 && updatedExample?.status < 600 ? updatedExample.status : 500;
          const responseObj = getContentAndType({ ...updatedExample });
 
          response.set('Cache-Control', 'no-cache');
 
          Iif (httpStatus < 500 && Array.isArray(header?.fields?.Header)) {
            let isAuthorized = true;
 
            header?.fields?.Header?.forEach(headerValue => {
              if (!headerValue.optional && headerValue.field && /authorization/i.test(headerValue.field)) {
                const authorization = request.get('authorization');
 
                if (!authorization) {
                  const authResponseObj = getContentAndType({ ...updatedAuthExample });
                  const forcedStatus = 401;
 
                  response.append('WWW-Authenticate', 'Spoof response');
                  response.status(forcedStatus);
                  response.set('Content-Type', authResponseObj.contentType);
 
                  if (mockSettings?.delay > 0) {
                    logger.info(`waiting\t:${forcedStatus} :${authResponseObj.contentType} :${url}`);
                  }
 
                  setTimeout(() => {
                    logger.info(`response\t:${forcedStatus} :${authResponseObj.contentType} :${url}`);
                    response.end(authResponseObj.content || 'Authorization Required');
                  }, mockSettings?.delay || 0);
 
                  isAuthorized = false;
                }
              }
            });
 
            if (isAuthorized === false) {
              return;
            }
          }
 
          response.status(httpStatus);
          response.set('Content-Type', responseObj.contentType);
 
          Iif (mockSettings?.delay > 0) {
            logger.info(`waiting\t:${httpStatus} :${responseObj.contentType} :${url}`);
          }
 
          setTimeout(() => {
            logger.info(`response\t:${httpStatus} :${responseObj.contentType} :${url}`);
            response.send(responseObj.content);
          }, mockSettings?.delay || 0);
        }
      });
 
      routesLoaded += 1;
    } catch (e) {
      logger.warn(`response\t:${e.message}`);
    }
  });
 
  return {
    appResponses,
    routesLoaded: routesLoaded > 0
  };
};
 
/**
 * Open request headers up. Parse OPTIONS or continue
 *
 * @param {object} request
 * @param {object} response
 * @param {Function} next
 */
const buildRequestHeaders = (request, response, next) => {
  const hasOrigin = request.headers.origin != null;
 
  response.set('Access-Control-Allow-Origin', hasOrigin ? request.headers.origin : '*');
  response.set('Access-Control-Allow-Credentials', !hasOrigin);
  response.set('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, HEAD, OPTIONS, PATCH');
 
  const requestHeaders = request.headers['access-control-request-headers'];
 
  if (requestHeaders !== null && requestHeaders !== undefined) {
    response.set('Access-Control-Allow-Headers', requestHeaders);
  }
 
  if (request.method === 'OPTIONS') {
    response.end();
  } else {
    next();
  }
};
 
module.exports = { buildResponse, buildRequestHeaders, getContentAndType, getCustomMockSettings, getExampleResponse };