Repository navigation
Expand file tree
/
Copy pathbaseTransport.ts
More file actions
254 lines (229 loc) · 7.96 KB
/
Copy pathbaseTransport.ts
File metadata and controls
254 lines (229 loc) · 7.96 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* eslint-disable no-console */
import {
StatusCode,
addQueryParams,
agentPrefix,
mergeOptions,
LookerAppId,
sdkTimeout,
} from './transport';
import { stripTrailingSlashes } from './constants';
import type {
Authenticator,
HttpMethod,
IRawRequest,
IRawResponse,
ITransport,
ITransportSettings,
RawObserver,
SDKResponse,
Values,
IRequestProps,
} from './transport';
export abstract class BaseTransport implements ITransport {
protected constructor(protected readonly options: ITransportSettings) {
this.options = options;
}
observer: RawObserver | undefined = undefined;
abstract parseResponse<TSuccess, TError>(
raw: IRawResponse
): Promise<SDKResponse<TSuccess, TError>>;
ok(res: IRawResponse): boolean {
return (
res.statusCode >= StatusCode.OK && res.statusCode <= StatusCode.IMUsed
);
}
/**
* HTTP request function for atomic, fully downloaded raw HTTP responses
*
* NOTE: This method has no error handling. It simply returns the results of the HTTP request.
*
* @param method of HTTP request
* @param path request path, either relative or fully specified
* @param queryParams name/value pairs to pass as part of the URL
* @param body data for the body of the request
* @param authenticator authenticator callback, typically from `IAuthSession` implementation
* @param options overrides of default transport settings
* @returns typed response of `TSuccess`, or `TError` result
*/
abstract rawRequest(
method: HttpMethod,
path: string,
queryParams?: Values,
body?: any,
authenticator?: Authenticator,
options?: Partial<ITransportSettings>
): Promise<IRawResponse>;
/**
* Request a streaming response
* @param method HTTP method
* @param path Request path
* @param queryParams query parameters for the request
* @param body http body to include with request
* @param authenticator callback to add authentication information to the request
* @param options transport settings overrides
*/
abstract request<TSuccess, TError>(
method: HttpMethod,
path: string,
queryParams?: any,
body?: any,
authenticator?: Authenticator,
options?: Partial<ITransportSettings>
): Promise<SDKResponse<TSuccess, TError>>;
/**
* Request a streaming response
* @param callback A function will be called with the created HTTP response object
* @param method HTTP method
* @param path Request path
* @param queryParams parameters for the request
* @param body http body to include with request
* @param authenticator callback to add authentication information to the request
* @param options transport settings overrides
* @returns the streaming response
*/
abstract stream<TSuccess>(
callback: (response: Response) => Promise<TSuccess>,
method: HttpMethod,
path: string,
queryParams?: Values,
body?: any,
authenticator?: Authenticator,
options?: Partial<ITransportSettings>
): Promise<TSuccess>;
/**
* Determine whether the url should be an API path, relative from base_url, or is already fully specified override
* @param path Request path
* @param options Transport settings
* @param queryParams Collection of query Params
* @returns the fully specified request path including any query string parameters
*/
makeUrl(
path: string,
options: Partial<ITransportSettings>,
queryParams?: Values
) {
// is this an API-versioned call?
const base = stripTrailingSlashes(options.base_url);
if (!path.match(/^(http:\/\/|https:\/\/)/gi)) {
path = `${base}${path}`; // path was relative
}
path = addQueryParams(path, queryParams);
return path;
}
abstract retry(wait: IRawRequest): Promise<IRawResponse>;
protected async initRequest(
method: HttpMethod,
path: string,
body?: any,
authenticator?: Authenticator,
options?: Partial<ITransportSettings>
) {
const agentTag = options?.agentTag || this.options.agentTag || agentPrefix;
const agent = { headers: { [LookerAppId]: agentTag } };
options = mergeOptions({ ...this.options, ...agent }, options ?? {});
const headers = options.headers ?? {};
// Make sure an empty body is undefined
if (!body) {
body = undefined;
} else {
if (typeof body !== 'string') {
let isUrlEncoded = body instanceof URLSearchParams;
if (!isUrlEncoded) {
isUrlEncoded = Object.keys(headers).some(
k =>
k.toLowerCase() === 'content-type' &&
headers[k]
?.toString()
.includes('application/x-www-form-urlencoded')
);
}
if (isUrlEncoded) {
if (body instanceof URLSearchParams) {
body = body.toString();
} else {
const params = new URLSearchParams();
Object.entries(body as any).forEach(([k, v]) => {
if (v !== undefined && v !== null) {
params.append(
k,
v instanceof Date
? v.toISOString()
: typeof v === 'object'
? JSON.stringify(v)
: v.toString()
);
}
});
body = params.toString();
}
if (!headers['Content-Type']) {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
} else {
body = JSON.stringify(body);
headers['Content-Type'] = 'application/json';
}
}
}
let signaller;
if (AbortSignal.timeout) {
const ms = sdkTimeout(options) * 1000;
let signaller = AbortSignal.timeout(ms);
if ('signal' in options && options.signal) {
// AbortSignal.any may not be available, tolerate its absence
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (AbortSignal.any) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
signaller = AbortSignal.any([options.signal, signaller]);
} else {
console.debug(
'Cannot combine cancel signal and timeout. AbortSignal.any is not available in this transport.'
);
console.debug({ AbortSignal });
}
} else {
console.debug(
'AbortSignal.timeout is not defined. Timeout will use default behavior'
);
}
}
let props: IRequestProps = {
body,
credentials: 'same-origin',
headers,
method,
url: path,
signal: signaller,
};
if (authenticator) {
// Add authentication information to the request
props = await authenticator(props);
}
// Transform to HTTP request headers at the last second
// props.headers = new Headers(props.headers) as any;
return props;
}
}