const {generateEgTunnelError} = require('./eg-tunnel-errors')

module.exports = async function (request) {
  let data, error
  try {
    const result = await request

    data = await _extractData(result)

    if (!result.ok) {
      error = generateEgTunnelError(data, result.status)
    }
  } catch (e) {
    error = generateEgTunnelError(e, 500)
  }

  if (error) {
    throw error
  }

  return data
}

async function _extractData(result) {
  const contentType = result.headers.get('content-type')
  try {
    if (contentType && contentType.indexOf('application/json') !== -1) {
      return await result.json()
    } else {
      return {message: await result.text()}
    }
  } catch (e) {
    throw {message: `Failed to parse the data from the server`}
  }
}
