/*! * Copyright (c) 2020 Ville de Montreal. All rights reserved. * Licensed under the MIT license. * See LICENSE file in the project root for full license information. */ import { AxiosRequestConfig } from 'axios'; import { IHttpRequestCorrelator } from '@villedemontreal/auth-core'; import { IAxiosPlugin } from './IAxiosPlugin'; import { makeAxiosPlugin } from './makeAxiosPlugin'; import { getHeader } from './requestUtils'; /** * plugin that will automatically inject a correlation ID generated by the * submitted provider into the standard "x-correlation-id" header. * Note that your correlation ID provider should rely on CLS (Continuation Local Storage) * to make the current correlation ID available to any async hooks created from * the incoming HTTP request. * @param correlator the correlator used to tag outgoing requests with a Correlation-ID header. * @example * const correlator = new HttpRequestCorrelator(); * const config: AxiosRequestConfig = { * url: 'http://localhost:4004/secured/profile' * }; * requestCorrelator(correlator).bind(config); * requestLogger(new ConsoleLogger(() => correlator.getId())).bind(config); * const response = await axios.request(config); */ export function requestCorrelator( correlator: IHttpRequestCorrelator, ): IAxiosPlugin { return makeAxiosPlugin({ //-------------------------------------------------------------------- onStart(config: AxiosRequestConfig): Promise { if (!getHeader(config, 'x-correlation-id')) { const value = correlator.getId(); if (value) { config.headers = { ...config.headers, ['x-correlation-id']: value, }; } } return Promise.resolve(); }, }); }