generated from VilledeMontreal/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
requestCorrelator.ts
46 lines (45 loc) · 1.71 KB
/
requestCorrelator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*!
* 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<void> {
if (!getHeader(config, 'x-correlation-id')) {
const value = correlator.getId();
if (value) {
config.headers = {
...config.headers,
['x-correlation-id']: value,
};
}
}
return Promise.resolve();
},
});
}