-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbaseCogniteClient.ts
374 lines (336 loc) · 10.1 KB
/
baseCogniteClient.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
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright 2020 Cognite AS
import isString from 'lodash/isString';
import { version } from '../package.json';
import {
AUTHORIZATION_HEADER,
X_CDF_APP_HEADER,
X_CDF_SDK_HEADER,
} from './constants';
import type { HttpResponse } from './httpClient/basicHttpClient';
import { CDFHttpClient } from './httpClient/cdfHttpClient';
import type { HttpHeaders } from './httpClient/httpHeaders';
import {
type RetryValidator,
createUniversalRetryValidator,
} from './httpClient/retryValidator';
import type { RetryableHttpRequestOptions } from './httpClient/retryableHttpClient';
import { MetadataMap } from './metadata';
import {
type CogniteAPIVersion,
bearerString,
getBaseUrl,
projectUrl,
} from './utils';
export interface ClientOptions {
/**
* App identifier (ex: 'FileExtractor')
* This is a free-text string that will be used to identify your application.
*/
appId: string;
/** URL to Cognite cluster, e.g 'https://greenfield.cognitedata.com' **/
baseUrl?: string;
/** Project name */
project: string;
/**
* @deprecated Use {@link oidcTokenProvider} instead.
*/
getToken?: () => Promise<string>;
/**
* Will be invoked when the SDK needs to authenticate against the CDF API.
* The function should return a valid access token to be used against the CDF API.
* The function will be called when the API returns 401 (Unauthorized) or when
* someone calls {@link BaseCogniteClient.authenticate}.
*
* It is the responsibility of the user to get hold of a valid access token to pass into the SDK.
*
* @returns A string representing the raw access token to be used against the CDF API.
*/
oidcTokenProvider?: () => Promise<string>;
/**
* Used to override the default retry validator.
*/
retryValidator?: RetryValidator;
}
export function accessApi<T>(api: T | undefined): T {
if (api === undefined) {
throw Error('API not found');
}
return api;
}
export default class BaseCogniteClient {
private readonly apiVersion: CogniteAPIVersion;
private readonly http: CDFHttpClient;
private readonly metadata: MetadataMap;
private readonly getOidcToken: () => Promise<string | undefined>;
readonly project: string;
private retryValidator: RetryValidator;
/**
* To prevent calling `getToken` method multiple times in parallel, we set
* the promise that `getToken` returns to a variable and check its existence
* on function calls for `authenticate`.
*/
private tokenPromise?: Promise<string | undefined>;
private isTokenPromiseFulfilled?: boolean;
/**
* Create a new SDK client
*
* @param options Client options
*
* ```js
* import { CogniteClient } from '@cognite/sdk';
*
* const client = new CogniteClient({ appId: 'YOUR APPLICATION NAME' });
*
* // can also specify a base URL
* const client = new CogniteClient({ ..., baseUrl: 'https://greenfield.cognitedata.com' });
* ```
*/
constructor(options: ClientOptions, apiVersion: CogniteAPIVersion = 'v1') {
if (!options) {
throw Error('`CogniteClient` is missing parameter `options`');
}
if (!isString(options.appId)) {
throw Error('options.appId is required and must be of type string');
}
if (!isString(options.project)) {
throw Error('options.project is required and must be of type string');
}
if (options.getToken && options.oidcTokenProvider) {
throw Error(
'options.getToken and options.oidcTokenProvider are mutually exclusive. Please only provide options.oidcTokenProvider'
);
}
if (!options.getToken && !options.oidcTokenProvider) {
throw Error(
'options.oidcTokenProvider is required and must be of type () => Promise<string>'
);
}
if (options.getToken) {
console.warn(
'options.getToken is deprecated and has been renamed to `options.oidcTokenProvider`.'
);
}
const { baseUrl } = options;
this.retryValidator =
options.retryValidator ?? createUniversalRetryValidator();
this.http = this.initializeCDFHttpClient(baseUrl, options);
this.metadata = new MetadataMap();
this.apiVersion = apiVersion;
this.project = options.project;
this.getOidcToken = async () => {
if (options.oidcTokenProvider) {
return options.oidcTokenProvider();
}
if (options.getToken) {
return options.getToken();
}
};
this.initAPIs();
}
public authenticate: () => Promise<string | undefined> = async () => {
try {
const token = await this.authenticateUsingOidcTokenProvider();
return token;
} catch (e) {
return;
}
};
private authenticateUsingOidcTokenProvider: () => Promise<
string | undefined
> = async () => {
try {
if (!this.tokenPromise || this.isTokenPromiseFulfilled) {
this.isTokenPromiseFulfilled = false;
this.tokenPromise = this.getOidcToken();
}
const token = await this.tokenPromise;
this.isTokenPromiseFulfilled = true;
if (token === undefined) return token;
const bearer = bearerString(token);
this.httpClient.setDefaultHeader(AUTHORIZATION_HEADER, bearer);
return token;
} catch {
return;
}
};
private initializeCDFHttpClient(
baseUrl: string | undefined,
options: ClientOptions
) {
const httpClient = new CDFHttpClient(
getBaseUrl(baseUrl),
this.getRetryValidator()
);
httpClient
.setDefaultHeader(X_CDF_APP_HEADER, options.appId)
.setDefaultHeader(
X_CDF_SDK_HEADER,
`CogniteJavaScriptSDK:${this.version}`
);
httpClient.set401ResponseHandler(async (_, request, retry, reject) => {
try {
const requestToken = this.retrieveTokenValueFromHeader(request.headers);
const currentToken = await this.tokenPromise;
const newToken =
currentToken !== requestToken
? currentToken
: await this.authenticate();
if (newToken && newToken !== requestToken) {
retry();
} else {
reject();
}
} catch {
reject();
}
});
return httpClient;
}
/**
* It retrieves the previous token from header
* @returns string
*/
private retrieveTokenValueFromHeader(
headers?: HttpHeaders
): string | undefined {
const token = headers?.[AUTHORIZATION_HEADER];
return token !== undefined ? token.replace('Bearer ', '') : token;
}
/**
* Returns the base-url used for all requests.
*/
public getBaseUrl(): string {
return this.httpClient.getBaseUrl();
}
/**
* Returns the default HTTP request headers, including e.g. authentication
* headers that is included in all requests. Headers provided per-requests is not
* included in this list. This function is useful when constructing API requests
* outside the SDK.
*
* ```js
* const customUrl = '...';
* const headers = client.getDefaultRequestHeaders();
* const result = await fetch(customUrl, { headers });
* ```
*/
public getDefaultRequestHeaders(): HttpHeaders {
return { ...this.httpClient.getDefaultHeaders() };
}
/**
* Lookup response metadata from an request using the response as the parameter
*
* ```js
* const createdAsset = await client.assets.create([{ name: 'My first asset' }]);
* const metadata = client.getMetadata(createdAsset);
* ```
*/
public getMetadata = (value: object) => this.metadataMap.get(value);
/**
* Basic HTTP method for GET
*
* @param path The URL path
* @param options Request options, optional
*
* ```js
* const response = await client.get('/api/v1/projects/{project}/assets', { params: { limit: 50 }});
* ```
*/
public get = <T = unknown>(
path: string,
options?: RetryableHttpRequestOptions
) => this.httpClient.get<T>(path, options);
/**
* Basic HTTP method for PUT
*
* @param path The URL path
* @param options Request options, optional
*
* ```js
* const response = await client.put('someUrl');
* ```
*/
public put = <T = unknown>(
path: string,
options?: RetryableHttpRequestOptions
) => this.httpClient.put<T>(path, options);
/**
* Basic HTTP method for POST
*
* @param path The URL path
* @param options Request options, optional
*
* ```js
* const assets = [{ name: 'First asset' }, { name: 'Second asset' }];
* const response = await client.post('/api/v1/projects/{project}/assets', { data: { items: assets } });
* ```
*/
public post = <T = unknown>(
path: string,
options?: RetryableHttpRequestOptions
) => this.httpClient.post<T>(path, options);
/**
* Basic HTTP method for DELETE
*
* @param path The URL path
* @param options Request options, optional
* ```js
* const response = await client.delete('someUrl');
* ```
*/
public delete = <T = unknown>(
path: string,
options?: RetryableHttpRequestOptions
) => this.httpClient.delete<T>(path, options);
/**
* Basic HTTP method for PATCH
*
* @param path The URL path
* @param options Request options, optional
* ```js
* const response = await client.patch('someUrl');
* ```
*/
public patch = <T = unknown>(
path: string,
options?: RetryableHttpRequestOptions
) => this.httpClient.patch<T>(path, options);
protected initAPIs() {
// will be overritten by subclasses
}
/**
* Returns the retry validator to be used in the http client.
* Override to provide a better validator
*/
protected getRetryValidator(): RetryValidator {
return this.retryValidator;
}
protected get version() {
return `${version}-core`;
}
protected apiFactory = <ApiType>(
api: new (
relativePath: string,
httpClient: CDFHttpClient,
map: MetadataMap
) => ApiType,
relativePath: string
) => {
return new api(
`${this.projectUrl}/${relativePath}`,
this.httpClient,
this.metadataMap
);
};
protected get projectUrl() {
return projectUrl(this.project, this.apiVersion);
}
protected get metadataMap() {
return this.metadata;
}
protected get httpClient() {
return this.http;
}
}
export type BaseRequestOptions = RetryableHttpRequestOptions;
export type Response = HttpResponse<unknown>;