all files / axway/lib/ requestHandler.js

92.37% Statements 109/118
96.67% Branches 58/60
100% Functions 0/0
92.98% Lines 106/114
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                                                                                                                                                                                                                                                                                                                                                                 
'use strict';
 
const http = require('http');
const https = require('https');
// const fs = require('fs');
// const uuid = require('node-uuid');
// const AWS = require('aws-sdk');
const _ = require('lodash');
const request = require('request');
// const rmdir = require('rimraf');
const jdbc = require('./jdbc');
const xml2js = require('xml2js');
const responseHandler = require('./responseHandler');
const util = require('./util');
 
const jsonRequestHandler = (context, output) => {
 
  if(util.notNull(output.replBody) && util.notNull(output.bodyTokens)) {
    if(typeof(output.replBody) === 'string') {
      _.forEach(output.bodyTokens, (value, key) => {
        const wrappedKey = `{${key}}`;
        if(output.replBody.includes(wrappedKey)) {
          const re = new RegExp(wrappedKey, 'g');
          output.replBody = output.replBody.replace(re, JSON.stringify(value));
        }
      });
      // Definitely NOT a security concern /s
      const replBody = eval("(" + output.replBody + ")"); // jshint ignore:line
      output.body = replBody;
    } else {
      output.body = util.tokenRepl(output.body, output.bodyTokens);
    }
    output.runPreRequestHooks(output);
  }
 
  if(util.notNull(output.body)) {
    var keys = Object.keys(output.body);
    if(keys !== null && keys.length > 0) {
      output.headers['Content-Length'] = Buffer.byteLength(JSON.stringify(output.body), 'utf-8');
    }
  }
 
  const outCtx = {
    succeed: o => {
      const end = new Date().getTime();
      console.log("vendor success in", (end - start));
      return context.succeed(o);
    },
    fail: e => {
      const end = new Date().getTime();
      console.log("vendor fail in", (end - start));
      context.fail(e);
    },
    done: (e, o) => {
      const end = new Date().getTime();
      console.log("vendor done in", (end - start));
      context.done(e, o);
    }
  };
 
  const start = new Date().getTime();
 
  let conn;
  if (output.protocol.startsWith('https')) {
 
    // console.log("making request", {
    //   headers: output.headers,
    //   protocol: output.protocol,
    //   body: output.body,
    //   host: output.host,
    //   hostname: output.hostname,
    //   method: output.method,
    //   path: output.path
    // });
 
    conn = https.request(output);
  } else {
    conn = http.request(output);
  }
 
  conn.on('error', err => { context.fail(util.failure(400, err)); });
  conn.on('response', jsonBackHandler(outCtx, output));
 
  if (util.notNull(output.body)) { conn.write(JSON.stringify(output.body)); }
 
  conn.setTimeout(10000, () => {
    context.fail(util.failure(504, 'Request timed out'));
  });
 
  conn.end();
};
 
const jsonBackHandler = (context, output) => res => {
  let rawBody = "";
  res.on('readable', () => {
    const data = res.read();
    if (typeof(data) !== 'undefined' && data !== null) {
      rawBody += data;
    }
  });
 
  res.on('end', () => {
    if (res.statusCode >= 200 && res.statusCode <= 207) {
      const handler = responseHandler.getResponseHandler(res.headers);
      handler(res, rawBody, context, output);
    } else {
      context.done(util.failure(res.statusCode, rawBody, res.statusMessage));
    }
  });
 
  res.on('error', err => context.fail({error: err.toString()}));
};
 
const soapRequestHandler = (context, output) => {
  const soapEnvelope = 'soapenv:Envelope';
  const soapBody = 'soapenv:Body';
  const soapHeader = 'soapenv:Header';
 
  xml2js.parseString(output.body, (err, result) => {
    const envelope = result[soapEnvelope];
 
    if(util.notNull(envelope)) {
      if(util.notNull(envelope[soapBody]) && typeof envelope[soapBody] === 'object') {
        envelope[soapBody] = util.tokenRepl(envelope[soapBody], output.bodyTokens);
      }
 
      if(util.notNull(envelope[soapHeader])) {
        envelope[soapHeader] = util.tokenRepl(envelope[soapHeader], output.bodyTokens);
      }
 
      result[soapEnvelope] = envelope;
    }
 
    const builder = new xml2js.Builder();
    output.body = builder.buildObject(result);
 
    const method = output.method ? output.method.toLowerCase() : 'post';
    const reqOptions = {
      url: output.findConfig('base.url') + output.pathname,
      headers: output.headers,
      body: output.body,
    };
 
    request[method](reqOptions, (err, res, body) => {
      if (res.statusCode >= 200 && res.statusCode <= 207) {
        const handler = responseHandler.getResponseHandler(res.headers, 'soap');
        handler(res, body, context, output);
      } else {
        context.fail(util.failure(res.statusCode, err));
      }
    });
  });
 
};
 
const jdbcRequestHandler = (context, output) => {
  jdbc.send(context, output);
};
 
const multipartRequestHandler = (context, output) => {
 
  // fetchS3File(context, output)
  //   .then( tmpPath => {
  //     const formData = Object.assign({}, output.form, {
  //       file: fs.createReadStream(tmpPath + output.file.Key),
  //     });
  //
  //     const method = output.method.toLowerCase();
  //
  //     const reqOptions = {
  //       url: output.protocol + '//' + output.hostname + output.pathname,
  //       formData: formData,
  //       headers: output.headers,
  //     };
  //
  //     request[method](reqOptions, (err, res, body) => {
  //       if(!err) {
  //         rmdir(tmpPath, () => {
  //           if (res.statusCode >= 200 && res.statusCode <= 207) {
  //             const handler = responseHandler.getResponseHandler(res.headers);
  //             handler(res, body, context, output);
  //           }
  //         });
  //       } else {
  //         context.fail(util.failure(400, err));
  //       }
  //     });
  //   })
  //   .catch( error => {
  //     context.fail(error);
  //   });
};
 
const encodedUploadHandler = (context, output) => {
  // fetchS3File(context, output)
  //   .then(tmpPath => {
  //     const filePayload = {
  //       name: output.file.Key,
  //       body: fs.readFileSync(tmpPath + output.file.Key, { encoding: 'base64' }),
  //       // type: mime.lookup(output.file.Key),
  //       // size: fs.statSync(tmpPath + output.file.Key).size,
  //     };
  //
  //     output.body = Object.assign({}, filePayload, output.body, output.form);
  //     output.headers['Content-Type'] = 'application/json';
  //     output.runPreRequestHooks(output);
  //    // This is a JSON request now, so hand it off to the JSON handler, yeah?
  //    jsonRequestHandler(context, output);
  //
  //   })
  //   .catch( error => {
  //     context.fail(error);
  //   });
};
 
 
// When we've decided that execution should halt
// by passing shouldContinue === false
const stopExecutionHandler = (context, output) => {
  const convertedResponse = output.convertResponse({
    body: JSON.stringify(output.responseBody),
    status: 'Bad Request',
    statusCode: output.statusCode
  });
  const errors = convertedResponse.body.errors || convertedResponse.body;
  context.done(util.failure(convertedResponse.statusCode, JSON.stringify(errors), 'Bad Request'), convertedResponse);
};
 
// Determines how to make the request to the vendor
// Usually based on the content-type but some previous logic
// may define the handler for special circumstances by attaching
// it to `output.requestHandler`
const getRequestHandler = (context, output) => {
  output.headers['Content-Type'] = output.headers['Content-Type'] || 'application/json';
  const contentType = output.headers['Content-Type'].split(';')[0].toLowerCase();
  let handler;
 
  if(output.shouldContinue === false) {
    console.log('using stopExecutionHandler');
    return stopExecutionHandler;
  }
 
 
  if(output.element.protocolType === 'soap') {
    return soapRequestHandler;
  } else if(output.element.protocolType === 'jdbc') {
    return jdbcRequestHandler;
  }
 
  if(util.notNull(output.reqHandler)) {
    switch(output.reqHandler) {
      case 'encodedUpload':
        console.warn('encodedUploadHandler handler temporarily unavailable');
        handler = encodedUploadHandler;
        break;
      default:
        console.warn('An explicit handler was assigned to `output` but not defined in `requestHandler.js`');
    }
  } else {
    switch(contentType) {
      case 'application/json':
      case 'application/jsonp':
        handler =  jsonRequestHandler;
        break;
      case 'multipart/form-data':
        console.warn('multipartRequestHandler handler temporarily unavailable');
        handler = multipartRequestHandler;
        break;
      default:
        console.warn('Request handler not found');
    }
  }
 
  if(!util.notNull(handler)) {
    handler = jsonRequestHandler;
  }
 
  return handler;
};
 
module.exports = {getRequestHandler, stopExecutionHandler, encodedUploadHandler,
                  multipartRequestHandler, soapRequestHandler, jsonRequestHandler, jdbcRequestHandler};