import { HttpHeaders } from '@angular/common/http'; export interface HeaderOptions { readonly authorization?: boolean; readonly accept?: boolean; readonly contentType?: boolean; } export class HeadersConfiguration { static getHeaders(options?: HeaderOptions): HttpHeaders { let headers = new HttpHeaders(); if (options?.accept === undefined || options.accept) { const httpHeaderAcceptSelected = HeadersConfiguration.selectHeaderAccept(['application/json']); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } } if (options?.contentType === undefined || options.contentType) { const httpContentTypeSelected = HeadersConfiguration.selectHeaderContentType(['application/json']); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } } return headers; } /** * Select the correct content-type to use for a request. * Uses {@link HeadersConfiguration#isJsonMime} to determine the correct content-type. * If no content type is found return the first found type if the contentTypes is not empty * @param contentTypes - the array of content types that are available for selection * @returns the selected content-type or undefined if no selection could be made. */ static selectHeaderContentType(contentTypes: string[]): string | undefined { if (contentTypes.length === 0) { return undefined; } const type = contentTypes.find(x => this.isJsonMime(x)); if (type === undefined) { return contentTypes[0]; } return type; } /** * Select the correct accept content-type to use for a request. * Uses {@link HeadersConfiguration#isJsonMime} to determine the correct accept content-type. * If no content type is found return the first found type if the contentTypes is not empty * @param accepts - the array of content types that are available for selection. * @returns the selected content-type or undefined if no selection could be made. */ static selectHeaderAccept(accepts: string[]): string | undefined { if (accepts.length === 0) { return undefined; } const type = accepts.find(x => this.isJsonMime(x)); if (type === undefined) { return accepts[0]; } return type; } /** * Check if the given MIME is a JSON MIME. * JSON MIME examples: * application/json * application/json; charset=UTF8 * APPLICATION/JSON * application/vnd.company+json * @param mime - MIME (Multipurpose Internet Mail Extensions) * @return True if the given MIME is JSON, false otherwise. */ static isJsonMime(mime: string): boolean { // eslint-disable-next-line no-control-regex const jsonMime = new RegExp('^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); } }