1 | import * as request from 'request-promise';
|
2 |
|
3 | const BASE_JSON_OPTIONS = {
|
4 | json: true,
|
5 | };
|
6 |
|
7 | export type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
8 |
|
9 | export interface IRequestOptions {
|
10 | body?: {};
|
11 | qs?: {};
|
12 | headers?: {
|
13 | [key: string]: string,
|
14 | };
|
15 | }
|
16 |
|
17 | export interface IRequestContext {
|
18 | request: {
|
19 | headers?: {
|
20 | [key: string]: string,
|
21 | };
|
22 | };
|
23 | }
|
24 |
|
25 | export class RequestWrapper {
|
26 |
|
27 | private static buildUrl = (baseUrl: string, path: string) => {
|
28 | return `${baseUrl}${path}`;
|
29 | }
|
30 |
|
31 | private static interceptRequestError = error => {
|
32 |
|
33 | error.message = `${error.message} - ${error.options.url}`;
|
34 |
|
35 | throw error;
|
36 | }
|
37 |
|
38 | private static getMergedOptions = (options?: IRequestOptions, context?: IRequestContext): IRequestOptions => {
|
39 | if (!context || !options) {
|
40 | return options;
|
41 | }
|
42 |
|
43 |
|
44 | return Object.assign({}, options, {
|
45 | headers: Object.assign({}, options.headers ? options.headers : {}, {
|
46 | 'x-request-id': context.request.headers['x-request-id'],
|
47 | 'x-b3-traceid': context.request.headers['x-b3-traceid'],
|
48 | 'x-b3-spanid': context.request.headers['x-b3-spanid'],
|
49 | 'x-b3-parentspanid': context.request.headers['x-b3-parentspanid'],
|
50 | 'x-b3-sampled': context.request.headers['x-b3-sampled'],
|
51 | 'x-b3-flags': context.request.headers['x-b3-flags'],
|
52 | 'x-ot-span-context': context.request.headers['x-ot-span-context'],
|
53 | }),
|
54 | });
|
55 | }
|
56 |
|
57 | private baseUrl: string;
|
58 |
|
59 | constructor(baseUrl: string) {
|
60 | this.baseUrl = baseUrl;
|
61 | }
|
62 |
|
63 | public buildJsonRequest = (
|
64 | path: string, method: Method = 'GET', options?: IRequestOptions, context?: IRequestContext) => {
|
65 | return Object.assign({}, BASE_JSON_OPTIONS, {
|
66 | url: RequestWrapper.buildUrl(this.baseUrl, path),
|
67 | method,
|
68 | }, RequestWrapper.getMergedOptions(options, context));
|
69 | }
|
70 |
|
71 | |
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 | public async proxyJsonRequest<T>(path: string, method: Method = 'GET', options?: IRequestOptions): Promise<T> {
|
79 | return request(this.buildJsonRequest(path, method, options)).catch(RequestWrapper.interceptRequestError);
|
80 | }
|
81 |
|
82 | |
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 | public async proxyCorrelatedJsonRequest<T>(
|
90 | path: string,
|
91 | method: Method = 'GET',
|
92 | context: IRequestContext,
|
93 | options?: IRequestOptions,
|
94 | ): Promise<T> {
|
95 | return request(this.buildJsonRequest(path, method, options, context)).catch(RequestWrapper.interceptRequestError);
|
96 | }
|
97 | }
|
98 |
|
99 | export function createWrapper(baseUrl: string) {
|
100 | return new RequestWrapper(baseUrl);
|
101 | }
|