@mikezimm/fps-core-v7
Version:
Library of reusable core interfaces, types and constants migrated from fps-library-v2
42 lines • 1.66 kB
JavaScript
/**
* Converts a string representation of an object into a HeadersInit object.
* @param jsonString - The string representation of the headers object.
* @returns A HeadersInit object.
* @throws Error if the input is not a valid JSON object or cannot be converted.
*/
export function parseHeadersFromString(jsonString) {
if (!jsonString)
return { headers: null, error: '', string: jsonString };
try {
const parsed = JSON.parse(jsonString);
const headersObj = parseHeadersFromObject(parsed);
return { ...headersObj, string: jsonString };
}
catch (error) {
console.error(`Failed to parse headers: ${error.message}`);
return { headers: null, error: error.message, string: jsonString };
}
}
export function parseHeadersFromObject(jsonObject) {
if (typeof jsonObject !== 'object' || jsonObject === null || Array.isArray(jsonObject)) {
return { headers: null, error: 'Invalid headers jsonObject', jsonObject: jsonObject };
}
// Ensure all keys and values are strings
const headers = {};
try {
for (const key in jsonObject) {
if (Object.prototype.hasOwnProperty.call(jsonObject, key)) {
const value = jsonObject[key];
if (typeof value !== 'string') {
throw new Error(`Header value for "${key}" must be a string`);
}
headers[key] = value;
}
}
}
catch (error) {
console.log();
}
return { headers: headers, error: '', jsonObject: jsonObject };
}
//# sourceMappingURL=parseHeaders.js.map