const [processedUrl, processedParams] = await config.preMiddleware(requestUrl, requestParams)
const responseObject = await fetch(processedUrl, processedParams);

const responseContentType = responseObject.headers.get('Content-Type');

let responseJson = null;
const responseText = await responseObject.text();

if (responseContentType.startsWith('application/json') || responseContentType.startsWith('application/hal+json')) {
  responseJson = JSON.parse(responseText);
}

if (!responseObject.ok) {
  throw new ApiError({
    message: 'Api error while fetching {{operation.name}}',
    status: responseObject.status,
    statusText: responseObject.statusText,
    response: responseJson,
    headers: responseObject.headers,
  });
}

{{#if operation.responses}}
  const responseSchema = {{json operation.responses}};
  const responseStatus = responseObject.status;
  const acceptedContentTypes = responseSchema[responseStatus] && responseSchema[responseStatus].contentTypes;

  if (acceptedContentTypes
    && !acceptedContentTypes.includes(responseContentType)
    && (!responseContentType.startsWith('application/json')
      || !acceptedContentTypes.find(acceptedContentType => acceptedContentType.startsWith('application/json')))
  ) {
    throw new Error('Incorrect content type');
  }
{{/if}}


{{#if (and operation.responses options.validateResponse)}}
  function isResponse(obj) {
  const isValid = !responseSchema[responseStatus]
  || !responseSchema[responseStatus].response
  || ajv.validate(responseSchema[responseStatus].response, obj);

    return !!isValid;
  }

  if (responseContentType.startsWith('application/json') || responseContentType.startsWith('application/hal+json')) {
      if (!isResponse(responseJson)) {
        throw new ResponseValidationError({
          message: 'Response schema validation error',
          method: '{{operation.name}}',
          errors: ajv.errors || [],
        });
      }
  }
{{/if}}

return {
  json: responseJson,
  text: responseText,
  headers: responseObject.headers,
};
