@mikezimm/fps-core-v7
Version:
Library of reusable core interfaces, types and constants migrated from fps-library-v2
75 lines • 2.95 kB
JavaScript
/**
* copyHeadersToReturns:
*
* 2024-12-09: Created this function in order to copy headers object to the return results.
* Typescript was not liking just assigning it so ChatGPT suggested this as the most robust way to handle it.
*
* @param headers
* @returns
*/
export function copyHeadersToReturns(headers) {
if (headers instanceof Headers) {
// Convert Headers instance to a Record<string, string>
const record = {};
headers.forEach((value, key) => {
record[key] = value;
});
return record;
}
else if (Array.isArray(headers)) {
// Convert array of tuples to a Record<string, string>
return Object.fromEntries(headers);
}
else {
// Assume it's already a Record<string, string>
return headers;
}
}
/**
* Created to auto-detect endpoints requiring OdataV3 and alert if they are not set correctly
*/
const OData3Endpoints = ['_api/web/navigation/', '_api/search/query?',]; // '', '', '', '', '', '', '', '', '', '',
/**
* Returns an array of strings for any matching endpoints.
* In reality you should either get 1 or 0, not an array.
*
* @param fetchAPI
* @returns
*/
export function getOdata3Targets(fetchAPI) {
// Alternate logic for es6 and later: if ( OData3Endpoints.some( (partial: string) => fetchAPI.toLowerCase().includes(partial.toLowerCase())) === true ) {
const matches = OData3Endpoints.filter((partial) => fetchAPI.toLowerCase().includes(partial.toLowerCase()));
return matches;
}
/**
* createMinHeaders
*
* 2024-12-09: Created this function in order to create HeadersInit with proper typings
*
* @param digestValue
* @param headerContentType
* @returns
*/
export function createMinHeaders(fetchAPI, digestValue, headerContentType, verbose = false) {
const headers = {};
if (digestValue)
headers['X-RequestDigest'] = digestValue;
if (headerContentType)
headers['Content-Type'] = headerContentType;
const matches = getOdata3Targets(fetchAPI);
if (matches.length > 0) {
// https://github.com/fps-solutions/HubCon/issues/118 --- added the > -1 for this issue.
// https://github.com/fps-solutions/SP-API-Tester/issues/19 --- added headerContentType check before indexOf
if (headerContentType && headerContentType.indexOf('odata.metadata') > -1) {
alert(`This endpoint '${matches[0]}' should be OdataV3.0 but you have an v4.0 content type`);
}
;
headers['OData-Version'] = '3.0';
headers['Accept'] = verbose === true ? 'application/json;odata=verbose' : 'application/json;odata=nometadata';
}
else {
headers['Accept'] = verbose === false ? 'application/json;odata.metadata=none' : 'application/json;odata.metadata=full';
}
return headers;
}
//# sourceMappingURL=headerInitUtilities.js.map