import responseHandler from './responseHandler'; import getEnvelopeBody from './getEnvelopeBody'; import { appendQueryParameters } from './location'; import parseJSON from '../json/parseJson'; import type { NetworkResponse, RequestOptions, SerializableObject } from '../types'; const rnoContent = (method: string): boolean => /^(?:GET|HEAD)$/i.test(method); export default function fetchAdaptor( options: RequestOptions, ): Promise> { const method = options.method || 'GET'; const hasContent = !rnoContent(method); let url = options.url || window.location.href; let requestInit: RequestInit; if (options.envelope) { url = appendQueryParameters(url, { envelope: 'request' }); requestInit = { method: 'POST', headers: {}, credentials: 'same-origin', body: getEnvelopeBody(method, options.headers || {}, options.data), }; } else { requestInit = { method, headers: options.headers || {}, credentials: 'same-origin', }; if (options.data) { if (!hasContent) { url = appendQueryParameters(url, options.data as SerializableObject); } else { requestInit.body = JSON.stringify(options.data); requestInit.headers = { ...requestInit.headers, 'Content-Type': 'application/json', }; } } } return fetch(url, requestInit) .then((res) => Promise.all([res, res.text()])) .then(([res, body]) => responseHandler(res.status, parseJSON(body))); }