function getContextFromRequest()

in lib/parsers.js [52:126]


function getContextFromRequest(req, conf, type) {
  var captureBody = conf.captureBody === type || conf.captureBody === 'all';

  var context = {
    http_version: req.httpVersion,
    method: req.method,
    url: getUrlFromRequest(req),
    headers: undefined,
  };
  if (req.socket && req.socket.remoteAddress) {
    context.socket = {
      remote_address: req.socket.remoteAddress,
    };
  }

  if (conf.captureHeaders) {
    context.headers = redactKeysFromObject(
      req.headers,
      conf.sanitizeFieldNamesRegExp,
    );

    if (context.headers.cookie && context.headers.cookie !== REDACTED) {
      let cookies = cookie.parse(req.headers.cookie);
      cookies = redactKeysFromObject(
        cookies,
        conf.sanitizeFieldNamesRegExp,
        COOKIE_VAL_REDACTED,
      );
      try {
        context.headers.cookie = Object.keys(cookies)
          .map((k) => cookie.serialize(k, cookies[k]))
          .join('; ');
      } catch (_err) {
        // Fallback to full redaction if there is an issue re-serializing.
        context.headers.cookie = REDACTED;
      }
    }
  }

  var contentLength = parseInt(req.headers['content-length'], 10);
  var transferEncoding = req.headers['transfer-encoding'];
  var chunked =
    typeof transferEncoding === 'string' &&
    transferEncoding.toLowerCase() === 'chunked';
  var body = req.json || req.body || req.payload;
  var haveBody = body && (chunked || contentLength > 0);

  if (haveBody) {
    if (!captureBody) {
      context.body = '[REDACTED]';
    } else if (Buffer.isBuffer(body)) {
      context.body = '<Buffer>';
    } else {
      if (typeof body === 'string' && req.bodyIsBase64Encoded === true) {
        body = Buffer.from(body, 'base64').toString('utf8');
      }
      body = redactKeysFromPostedFormVariables(
        body,
        req.headers,
        conf.sanitizeFieldNamesRegExp,
      );
      if (typeof body !== 'string') {
        body = tryJsonStringify(body) || stringify(body);
      }
      context.body = body;
    }
  }

  // TODO: Tempoary fix for https://github.com/elastic/apm-agent-nodejs/issues/813
  if (context.url && context.url.port) {
    context.url.port = String(context.url.port);
  }

  return context;
}