forked from VilledeMontreal/authentication-nodejs-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
requestCorrelator.ts
42 lines (41 loc) · 1.59 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
/*!
* 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 { Request } from 'request';
import { IHttpRequestCorrelator } from '@villedemontreal/auth-core';
import { IRequestPlugin } from './IRequestPlugin';
import { makeRequestPlugin } from './makeRequestPlugin';
/**
* 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: request.CoreOptions = {
* url: 'http://localhost:4004/secured/profile'
* };
* requestCorrelator(correlator).bind(config);
* requestLogger(new ConsoleLogger(() => correlator.getId())).bind(config);
* const response = await request(config);
*/
export function requestCorrelator(
correlator: IHttpRequestCorrelator,
): IRequestPlugin {
return makeRequestPlugin({
//--------------------------------------------------------------------
onStart(req: Request): Promise<void> {
if (!req.getHeader('x-correlation-id')) {
const value = correlator.getId();
if (value) {
req.setHeader('x-correlation-id', value);
}
}
return Promise.resolve();
},
});
}