forked from openfga/js-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.ts
231 lines (204 loc) · 6.94 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/**
* JavaScript and Node.js SDK for OpenFGA
*
* API version: 1.x
* Website: https://openfga.dev
* Documentation: https://openfga.dev/docs
* Support: https://openfga.dev/community
* License: [Apache-2.0](https://github.com/openfga/js-sdk/blob/main/LICENSE)
*
* NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT.
*/
import { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { metrics } from "@opentelemetry/api";
import { Configuration } from "./configuration";
import type { Credentials } from "./credentials";
import {
FgaApiError,
FgaApiInternalError,
FgaApiAuthenticationError,
FgaApiNotFoundError,
FgaApiRateLimitExceededError,
FgaApiValidationError,
FgaError
} from "./errors";
import { setNotEnumerableProperty } from "./utils";
import { buildAttributes } from "./telemetry";
const meter = metrics.getMeter("@openfga/sdk", "0.6.2");
const durationHist = meter.createHistogram("fga-client.request.duration", {
description: "The duration of requests",
unit: "milliseconds",
});
const queryDurationHist = meter.createHistogram("fga-client.query.duration", {
description: "The duration of queries on the FGA server",
unit: "milliseconds",
});
/**
*
* @export
*/
export const DUMMY_BASE_URL = "https://example.com";
/**
*
* @export
* @interface RequestArgs
*/
export interface RequestArgs {
url: string;
options: any;
}
/**
*
* @export
*/
export const setBearerAuthToObject = async function (object: any, credentials: Credentials) {
const accessTokenHeader = await credentials.getAccessTokenHeader();
if (accessTokenHeader && !object[accessTokenHeader.name]) {
object[accessTokenHeader.name] = accessTokenHeader.value;
}
};
/**
*
* @export
*/
export const setSearchParams = function (url: URL, ...objects: any[]) {
const searchParams = new URLSearchParams(url.search);
for (const object of objects) {
for (const key in object) {
if (Array.isArray(object[key])) {
searchParams.delete(key);
for (const item of object[key]) {
searchParams.append(key, item);
}
} else {
searchParams.set(key, object[key]);
}
}
}
url.search = searchParams.toString();
};
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
const isJsonMime = (mime: string): boolean => {
// eslint-disable-next-line no-control-regex
const jsonMime = new RegExp("^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$", "i");
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === "application/json-patch+json");
};
/**
*
* @export
*/
export const serializeDataIfNeeded = function (value: any, requestOptions: any) {
const nonString = typeof value !== "string";
const needsSerialization = nonString
? isJsonMime(requestOptions.headers["Content-Type"])
: nonString;
return needsSerialization
? JSON.stringify(value !== undefined ? value : {})
: (value || "");
};
/**
*
* @export
*/
export const toPathString = function (url: URL) {
return url.pathname + url.search + url.hash;
};
type ObjectOrVoid = object | void;
export type CallResult<T extends ObjectOrVoid> = T & {
$response: AxiosResponse<T>
};
export type PromiseResult<T extends ObjectOrVoid> = Promise<CallResult<T>>;
/**
* Returns true if this error is returned from axios
* source: https://github.com/axios/axios/blob/21a5ad34c4a5956d81d338059ac0dd34a19ed094/lib/helpers/isAxiosError.js#L12
* @param err
*/
function isAxiosError(err: any): boolean {
return err && typeof err === "object" && err.isAxiosError === true;
}
function randomTime(loopCount: number, minWaitInMs: number): number {
const min = Math.ceil(2 ** loopCount * minWaitInMs);
const max = Math.ceil(2 ** (loopCount + 1) * minWaitInMs);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
export async function attemptHttpRequest<B, R>(
request: AxiosRequestConfig<B>,
config: {
maxRetry: number;
minWaitInMs: number;
},
axiosInstance: AxiosInstance,
): Promise<AxiosResponse<R> | undefined> {
let iterationCount = 0;
do {
iterationCount++;
try {
return await axiosInstance(request);
} catch (err: any) {
if (!isAxiosError(err)) {
throw new FgaError(err);
}
const status = (err as any)?.response?.status;
if (status === 400 || status === 422) {
throw new FgaApiValidationError(err);
} else if (status === 401 || status === 403) {
throw new FgaApiAuthenticationError(err);
} else if (status === 404) {
throw new FgaApiNotFoundError(err);
} else if (status === 429 || status >= 500) {
if (iterationCount >= config.maxRetry) {
// We have reached the max retry limit
// Thus, we have no choice but to throw
if (status === 429) {
throw new FgaApiRateLimitExceededError(err);
} else {
throw new FgaApiInternalError(err);
}
}
await new Promise(r => setTimeout(r, randomTime(iterationCount, config.minWaitInMs)));
} else {
throw new FgaApiError(err);
}
}
} while(iterationCount < config.maxRetry + 1);
}
/**
* creates an axios request function
*/
export const createRequestFunction = function (axiosArgs: RequestArgs, axiosInstance: AxiosInstance, configuration: Configuration, credentials: Credentials, methodAttributes: Record<string, unknown> = {}) {
configuration.isValid();
const retryParams = axiosArgs.options?.retryParams ? axiosArgs.options?.retryParams : configuration.retryParams;
const maxRetry:number = retryParams ? retryParams.maxRetry : 0;
const minWaitInMs:number = retryParams ? retryParams.minWaitInMs : 0;
const start = Date.now();
return async (axios: AxiosInstance = axiosInstance) : PromiseResult<any> => {
await setBearerAuthToObject(axiosArgs.options.headers, credentials!);
const axiosRequestArgs = {...axiosArgs.options, url: configuration.getBasePath() + axiosArgs.url};
const response = await attemptHttpRequest(axiosRequestArgs, {
maxRetry,
minWaitInMs,
}, axios);
const executionTime = Date.now() - start;
const data = typeof response?.data === "undefined" ? {} : response?.data;
const result: CallResult<any> = { ...data };
setNotEnumerableProperty(result, "$response", response);
const attributes = buildAttributes(response, configuration.credentials, methodAttributes);
if (response?.headers) {
const duration = response.headers["fga-query-duration-ms"];
if (duration !== undefined) {
queryDurationHist.record(parseInt(duration, 10), attributes);
}
}
durationHist.record(executionTime, attributes);
return result;
};
};