-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.ts
208 lines (190 loc) · 6.52 KB
/
common.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
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
/* tslint:disable */
/* eslint-disable */
/*
Test Automation (No submodules)
SDKs (no submodules) to test automation workflows.
The version of the OpenAPI document: 1.0.0
NOTE: This file is auto generated by Konfig (https://konfigthis.com).
*/
import { Configuration } from "./configuration";
import { RequiredError, RequestArgs } from "./base";
import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
import { requestAfterHook } from "./requestAfterHook";
import { requestBeforeUrlHook } from "./requestBeforeUrlHook";
import { readableStreamToString, AutomationTestWithSubmoduleError, parseIfJson } from "./error";
/**
*
* @export
*/
export const DUMMY_BASE_URL = 'https://example.com'
/**
*
* @throws {RequiredError}
* @export
*/
export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) {
if (paramValue === null || paramValue === undefined) {
throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`);
}
}
/**
*
* @export
*/
export const setApiKeyToObject = async function ({
object,
key,
type,
keyParamName,
configuration,
prefix
}: {
object: any
key?: string
type?: "Cookie"
keyParamName: string
configuration?: Configuration
prefix?: string
}) {
key = key ? key : keyParamName
let apiKey: string | null | undefined = null
if (configuration && configuration.apiKey) {
if (typeof configuration.apiKey === 'function')
apiKey = await configuration.apiKey(keyParamName)
else if (typeof configuration.apiKey === 'string')
apiKey = configuration.apiKey
else if (typeof configuration.apiKey === 'object') {
if (keyParamName in configuration.apiKey)
apiKey = configuration.apiKey[keyParamName]
} else
throw Error(
`Unexpected type ${typeof configuration.apiKey} for Configuration.apiKey`
)
}
if (!apiKey) return
object[key] = prefix !== undefined ? `${prefix}${apiKey}` : apiKey
if (type === "Cookie")
object[key] = `${keyParamName}=${object[key]}`
}
/**
*
* @export
*/
export const setBasicAuthToObject = function (object: any, configuration?: Configuration) {
if (configuration && (configuration.username || configuration.password)) {
object["auth"] = { username: configuration.username, password: configuration.password };
}
}
/**
*
* @export
*/
export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) {
if (configuration && configuration.accessToken) {
const accessToken = typeof configuration.accessToken === 'function'
? await configuration.accessToken()
: await configuration.accessToken;
object["Authorization"] = "Bearer " + accessToken;
}
}
function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void {
if (typeof parameter === "object") {
if (Array.isArray(parameter)) {
(parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key));
}
else {
Object.keys(parameter).forEach(currentKey =>
setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`)
);
}
}
else {
if (urlSearchParams.has(key)) {
urlSearchParams.append(key, parameter);
}
else {
urlSearchParams.set(key, parameter);
}
}
}
/**
*
* @export
*/
export const setSearchParams = function (url: URL, ...objects: any[]) {
const searchParams = new URLSearchParams(url.search);
setFlattenedQueryParams(searchParams, objects);
url.search = searchParams.toString();
}
/**
*
* @export
*/
export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) {
const nonString = typeof value !== 'string';
const needsSerialization = nonString && configuration && configuration.isJsonMime
? configuration.isJsonMime(requestOptions.headers['Content-Type'])
: nonString;
return needsSerialization
? JSON.stringify(value !== undefined ? value : {})
: (value || "");
}
/**
*
* @export
*/
export const toPathString = function (url: URL) {
return removeTrailingSlash(url.pathname) + url.search + url.hash
}
/**
* remove trailing slash from string
*/
export const removeTrailingSlash = function (url: string) {
return url.replace(/\/$/, "");
}
/**
* Wrap an axios request in a try/catch block to catch network errors and parse the response body
*/
async function wrapAxiosRequest<R>(makeRequest: () => Promise<R>): Promise<R> {
try {
return await makeRequest();
} catch (e) {
if (e instanceof AxiosError && e.isAxiosError) {
try {
const responseBody =
e.response?.data instanceof ReadableStream
? await readableStreamToString(e.response.data)
: e.response?.data
throw new AutomationTestWithSubmoduleError(e, parseIfJson(responseBody), e.response?.headers)
} catch (innerError) {
if (innerError instanceof ReferenceError) {
// Got: "ReferenceError: ReadableStream is not defined"
// This means we are in a Node environment so just throw the original error
throw new AutomationTestWithSubmoduleError(e, e.response?.data, e.response?.headers)
}
if (innerError instanceof AutomationTestWithSubmoduleError) {
// Got "AutomationTestWithSubmoduleError" from the above try block
throw innerError;
}
// Something unexpected happened: propagate the error
throw e
}
}
throw e
}
}
/**
*
* @export
*/
export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) {
return async <T = unknown, R = AxiosResponse<T>>(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => {
requestBeforeUrlHook({axiosArgs, basePath, configuration})
const url = (configuration?.basePath || basePath) + axiosArgs.url
await requestAfterHook({axiosArgs, basePath, url, configuration})
return wrapAxiosRequest(async () => await axios.request<T, R>({ ...axiosArgs.options, url }));
};
}
export function isBrowser() {
return typeof window !== "undefined"
}