-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.ts
More file actions
282 lines (258 loc) · 9.81 KB
/
Copy pathcommon.ts
File metadata and controls
282 lines (258 loc) · 9.81 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/* tslint:disable */
/* eslint-disable */
/*
Remote API
Talent is everywhere. Opportunity is not. Remote's mission is to create opportunity everywhere, empowering employers to find and hire the best talent, and enabling individuals to build financial and personal freedom.
Remote is a Global HR Platform that helps companies hire, manage, and pay their entire team — and more effectively compete in the modern global economy through our comprehensive set of core solutions including, HRIS, payroll, international employment, contractor management, and more.
Whether you're just starting your global journey, or looking to optimize your existing operations, sign up or book a demo - and see how Remote makes global HR simple.
The version of the OpenAPI document: 0.1.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, RemoteError, parseIfJson } from "./error";
import { jwtDecode } from "jwt-decode";
/**
*
* @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;
}
}
/**
*
* @export
*/
export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) {
if (configuration === undefined) return;
// Sets the OAuth2 authentication header for the request and saves the token for the next request
const authenticate = async () => {
if (configuration.oauthClientId && configuration.oauthClientSecret && configuration.accessToken === undefined) {
const token = await wrapAxiosRequest(async () => {
if (configuration.basePath === undefined) {
throw new Error("basePath must be set to use the oauth2 authentication");
}
const url = configuration.oauthTokenUrl ?? removeTrailingSlash(configuration.basePath) + "/auth/oauth2/token"
const oauthResponse = await axios.request({
url,
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
},
data: `grant_type=client_credentials&client_id=${configuration.oauthClientId}&client_secret=${configuration.oauthClientSecret}`,
});
const json = await oauthResponse.data;
// we expect the token value to be in the property "access_token". if that property does not exist
// on the response, then return the value of any property with the substring "token" in its name
const token = json.access_token ?? Object.keys(json).reduce((acc, key) => {
if (key.toLowerCase().includes("token")) {
return json[key];
}
return acc;
}, undefined);
return token
})
if (token === undefined)
throw new Error("Token not found in OAuth response")
configuration.accessToken = token
}
}
const getToken = async () => {
return typeof configuration.accessToken === "function"
? await configuration.accessToken(name, scopes)
: await configuration.accessToken;
}
const previousToken = await getToken()
/**
* Authenticate if the token is not set or if it is expired
*/
if (previousToken === undefined) {
await authenticate();
} else {
// check that the token is still valid
const decodedToken = jwtDecode(previousToken);
const currentTime = Date.now() / 1000;
if (decodedToken.exp !== undefined && decodedToken.exp < currentTime) {
await authenticate();
}
}
/**
* Set the token in the request
*/
const token = await getToken()
if (token !== undefined) {
object["Authorization"] = "Bearer " + token;
}
}
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 RemoteError(e, parseIfJson(responseBody))
} 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 RemoteError(e, e.response?.data)
}
if (innerError instanceof RemoteError) {
// Got "RemoteError" 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"
}