UNPKG

2.96 kBPlain TextView Raw
1import * as request from 'request-promise';
2
3const BASE_JSON_OPTIONS = {
4 json: true,
5};
6
7export type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
8
9export interface IRequestOptions {
10 body?: {};
11 qs?: {};
12 headers?: {
13 [key: string]: string,
14 };
15}
16
17export interface IRequestContext {
18 request: {
19 headers?: {
20 [key: string]: string,
21 };
22 };
23}
24
25export class RequestWrapper {
26
27 private static buildUrl = (baseUrl: string, path: string) => {
28 return `${baseUrl}${path}`;
29 }
30
31 private static interceptRequestError = error => {
32 // Append request url to error message
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 // Merge required options with tracing from request context
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 * Proxy standard JSON request
73 * @param path relative URL path
74 * @param method HTTP method
75 * @param options request options
76 * @deprecated Since 1.2.0. Use proxyCorrelatedJsonRequest<T> instead.
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 * Proxy standard JSON request
84 * @param path relative URL path
85 * @param method HTTP method
86 * @param context request context
87 * @param options request options
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
99export function createWrapper(baseUrl: string) {
100 return new RequestWrapper(baseUrl);
101}