function formatHttpResponse()

in packages/ecs-helpers/lib/http-formatters.js [164:197]


function formatHttpResponse (ecs, res) {
  if (res === undefined || res === null || typeof res !== 'object') {
    return false
  }
  if (res.raw && res.raw.res && typeof (res.raw.res.getHeaders) === 'function') {
    // This looks like a hapi request object (https://hapi.dev/api/#request),
    // use the raw Node.js http.ServerResponse that it references.
    res = res.raw.res
  }
  // Use duck-typing to check this is a `http.ServerResponse`-y object.
  if (!('statusCode' in res && typeof res.getHeaders === 'function')) {
    return false
  }

  const { statusCode } = res
  ecs.http = ecs.http || {}
  ecs.http.response = ecs.http.response || {}
  ecs.http.response.status_code = statusCode

  const headers = res.getHeaders()
  const hasHeaders = Object.keys(headers).length > 0
  if (hasHeaders === true) {
    // See https://github.com/elastic/ecs/issues/232 for discussion of
    // specifying headers in ECS.
    ecs.http.response.headers = Object.assign(ecs.http.response.headers || {}, headers)
    const cLen = Number(headers['content-length'])
    if (!isNaN(cLen)) {
      ecs.http.response.body = ecs.http.response.body || {}
      ecs.http.response.body.bytes = cLen
    }
  }

  return true
}