import type { RequestHeaders } from '../types'; export default function getEnvelopeBody( method: string, headers: Record = {}, data: unknown, ): string { const mappedHeaders: RequestHeaders = Object.entries(headers).reduce((acc, [key, val]) => { if (acc[key]) { acc[key].push(val); } else { acc[key] = [val]; } return acc; }, {} as RequestHeaders); // As per the Json type, `data` could be null. We don't want to send 'null' as the value of body // JSON.stringify will preserve that, whereas with 'undefined` the field is dropped during // serialization if (data) { return JSON.stringify({ method, headers: mappedHeaders, body: data, }); } return JSON.stringify({ method, headers: mappedHeaders, }); }