@cfworker/cosmos 4.0.0 → 4.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/commonjs/package.json +3 -0
  2. package/dist/{cjs → commonjs}/retry.js +2 -2
  3. package/dist/{types → commonjs}/util.d.ts +1 -1
  4. package/dist/esm/client.d.ts +144 -0
  5. package/dist/esm/package.json +3 -0
  6. package/dist/esm/response.d.ts +24 -0
  7. package/dist/esm/retry.d.ts +21 -0
  8. package/dist/esm/retry.js +1 -1
  9. package/dist/esm/session.d.ts +24 -0
  10. package/dist/esm/signer.d.ts +12 -0
  11. package/dist/esm/types.d.ts +62 -0
  12. package/dist/esm/util.d.ts +5 -0
  13. package/package.json +32 -26
  14. package/dist/tsconfig.cjs.tsbuildinfo +0 -1
  15. package/dist/tsconfig.tsbuildinfo +0 -1
  16. package/src/client.ts +0 -581
  17. package/src/response.ts +0 -59
  18. package/src/retry.ts +0 -45
  19. package/src/session.ts +0 -74
  20. package/src/signer.ts +0 -63
  21. package/src/types.ts +0 -82
  22. package/src/util.ts +0 -59
  23. /package/dist/{types → commonjs}/client.d.ts +0 -0
  24. /package/dist/{cjs → commonjs}/client.js +0 -0
  25. /package/dist/{types → commonjs}/index.d.ts +0 -0
  26. /package/dist/{cjs → commonjs}/index.js +0 -0
  27. /package/dist/{types → commonjs}/response.d.ts +0 -0
  28. /package/dist/{cjs → commonjs}/response.js +0 -0
  29. /package/dist/{types → commonjs}/retry.d.ts +0 -0
  30. /package/dist/{types → commonjs}/session.d.ts +0 -0
  31. /package/dist/{cjs → commonjs}/session.js +0 -0
  32. /package/dist/{types → commonjs}/signer.d.ts +0 -0
  33. /package/dist/{cjs → commonjs}/signer.js +0 -0
  34. /package/dist/{types → commonjs}/types.d.ts +0 -0
  35. /package/dist/{cjs → commonjs}/types.js +0 -0
  36. /package/dist/{cjs → commonjs}/util.js +0 -0
  37. /package/{src/index.ts → dist/esm/index.d.ts} +0 -0
package/src/client.ts DELETED
@@ -1,581 +0,0 @@
1
- import { FeedResponse, ItemResponse } from './response.js';
2
- import { defaultRetryPolicy, RetryContext, RetryPolicy } from './retry.js';
3
- import { DefaultSessionContainer, SessionContainer } from './session.js';
4
- import { getSigner, Signer } from './signer.js';
5
- import {
6
- Collection,
7
- ConnectionInfo,
8
- ConsistencyLevel,
9
- Database,
10
- Document,
11
- IndexingDirective,
12
- IndexingPolicy,
13
- OfferType,
14
- PartitionKeyDefinition,
15
- Resource
16
- } from './types.js';
17
- import {
18
- assertArg,
19
- escapeNonASCII,
20
- parseConnectionString,
21
- uri
22
- } from './util.js';
23
-
24
- export type CosmosClientConfig =
25
- | (ConnectionInfo & CosmosClientConfigBase)
26
- | ({
27
- /**
28
- * Cosmos DB connection string.
29
- * @example
30
- * "AccountEndpoint=https://xxxxxxxxxx.documents.azure.com:443/;AccountKey=xxxxxxxxxx;"
31
- */
32
- connectionString: string;
33
- } & CosmosClientConfigBase);
34
-
35
- interface CosmosClientConfigBase {
36
- /**
37
- * The retry policy to use when requests are throttled.
38
- */
39
- retryPolicy?: RetryPolicy;
40
-
41
- /**
42
- * Default consistency level for requests. This can be overriden on individual requests.
43
- * @default "Session"
44
- */
45
- consistencyLevel?: ConsistencyLevel;
46
-
47
- /**
48
- * Default database id. This can be overriden on individual requests.
49
- */
50
- dbId?: string;
51
-
52
- /**
53
- * Default collection id. This can be overriden on individual requests.
54
- */
55
- collId?: string;
56
-
57
- /**
58
- * Reads, writes, and stores session tokens for requests made with ConsistencyLevel is "Session".
59
- */
60
- sessions?: SessionContainer;
61
-
62
- /**
63
- * Enables cross partition queries. This can be overriden on individual queries. Defaults to true.
64
- */
65
- enableCrossPartitionQueries?: boolean;
66
-
67
- /**
68
- * System fetch function
69
- */
70
- fetch?: typeof fetch;
71
- }
72
-
73
- export class CosmosClient {
74
- private readonly endpoint: string;
75
- private readonly signer: Signer;
76
- private readonly retryPolicy: RetryPolicy;
77
- private readonly consistencyLevel: ConsistencyLevel;
78
- private readonly dbId: string | undefined;
79
- private readonly collId: string | undefined;
80
- private readonly enableCrossPartitionQueries: boolean;
81
- private readonly systemFetch: typeof fetch;
82
- public readonly sessions: SessionContainer;
83
- public requestCharges = 0;
84
- public retries = { count: 0, delayMs: 0 };
85
-
86
- constructor(config: CosmosClientConfig) {
87
- let { endpoint, masterKey } =
88
- 'connectionString' in config
89
- ? parseConnectionString(config.connectionString)
90
- : config;
91
- if (endpoint.endsWith('/')) {
92
- endpoint = endpoint.slice(0, -1);
93
- }
94
- this.endpoint = endpoint;
95
- this.signer = getSigner(masterKey);
96
- this.retryPolicy = config.retryPolicy ?? defaultRetryPolicy;
97
- this.consistencyLevel = config.consistencyLevel ?? 'Session';
98
- this.dbId = config.dbId;
99
- this.collId = config.collId;
100
- this.enableCrossPartitionQueries =
101
- config.enableCrossPartitionQueries ?? true;
102
- this.sessions = config.sessions ?? new DefaultSessionContainer();
103
- this.systemFetch = config.fetch ?? fetch.bind(globalThis);
104
- }
105
-
106
- public async getDatabases(
107
- args: GetDatabasesArgs = {}
108
- ): Promise<FeedResponse<Database>> {
109
- const url = this.endpoint + `/dbs`;
110
- const request = new Request(url, { method: 'GET' });
111
- this.setHeaders(request.headers, args);
112
- const response = await this.fetchWithRetry(request);
113
- const next = this.getNext(response, args, this.getDatabases);
114
- return new FeedResponse<Database>(response, next, 'Databases');
115
- }
116
-
117
- public async getDatabase(
118
- args: GetDatabaseArgs = {}
119
- ): Promise<ItemResponse<Database>> {
120
- const { dbId = this.dbId, ...headers } = args;
121
- assertArg('dbId', dbId);
122
- const url = this.endpoint + uri`/dbs/${dbId}`;
123
- const request = new Request(url, { method: 'GET' });
124
- this.setHeaders(request.headers, headers);
125
- const response = await this.fetchWithRetry(request);
126
- return new ItemResponse<Database>(response);
127
- }
128
-
129
- public async getCollections(
130
- args: GetCollectionsArgs = {}
131
- ): Promise<FeedResponse<Collection>> {
132
- const { dbId = this.dbId, ...headers } = args;
133
- assertArg('dbId', dbId);
134
- const url = this.endpoint + uri`/dbs/${dbId}/colls`;
135
- const request = new Request(url, { method: 'GET' });
136
- this.setHeaders(request.headers, headers);
137
- const response = await this.fetchWithRetry(request);
138
- const next = this.getNext(response, args, this.getCollections);
139
- return new FeedResponse<Collection>(response, next, 'DocumentCollections');
140
- }
141
-
142
- public async getCollection(
143
- args: GetCollectionArgs = {}
144
- ): Promise<ItemResponse<Collection>> {
145
- const { dbId = this.dbId, collId = this.collId, ...headers } = args;
146
- assertArg('dbId', dbId);
147
- assertArg('collId', collId);
148
- const url = this.endpoint + uri`/dbs/${dbId}/colls/${collId}`;
149
- const request = new Request(url, { method: 'GET' });
150
- this.setHeaders(request.headers, headers);
151
- const response = await this.fetchWithRetry(request);
152
- return new ItemResponse<Collection>(response);
153
- }
154
-
155
- public async createCollection(
156
- args: CreateCollectionArgs
157
- ): Promise<ItemResponse<Collection>> {
158
- const {
159
- dbId = this.dbId,
160
- collId = this.collId,
161
- indexingPolicy,
162
- partitionKey,
163
- ...headers
164
- } = args;
165
- assertArg('dbId', dbId);
166
- assertArg('collId', collId);
167
- const url = this.endpoint + uri`/dbs/${dbId}/colls`;
168
- const body = JSON.stringify({ id: collId, indexingPolicy, partitionKey });
169
- const request = new Request(url, { method: 'POST', body });
170
- this.setHeaders(request.headers, headers);
171
- request.headers.set('content-type', 'application/json');
172
- const response = await this.fetchWithRetry(request);
173
- return new ItemResponse<Collection>(response);
174
- }
175
-
176
- public async replaceCollection(
177
- args: ReplaceCollectionArgs
178
- ): Promise<ItemResponse<Collection>> {
179
- const {
180
- dbId = this.dbId,
181
- collId = this.collId,
182
- indexingPolicy,
183
- partitionKey,
184
- ...headers
185
- } = args;
186
- assertArg('dbId', dbId);
187
- assertArg('collId', collId);
188
- const url = this.endpoint + uri`/dbs/${dbId}/colls/${collId}`;
189
- const body = JSON.stringify({ id: collId, indexingPolicy, partitionKey });
190
- const request = new Request(url, { method: 'PUT', body });
191
- this.setHeaders(request.headers, headers);
192
- request.headers.set('content-type', 'application/json');
193
- const response = await this.fetchWithRetry(request);
194
- return new ItemResponse<Collection>(response);
195
- }
196
-
197
- public async deleteCollection(
198
- args: DeleteCollectionArgs = {}
199
- ): Promise<Response> {
200
- const { dbId = this.dbId, collId = this.collId, ...headers } = args;
201
- assertArg('dbId', dbId);
202
- assertArg('collId', collId);
203
- const url = this.endpoint + uri`/dbs/${dbId}/colls/${collId}`;
204
- const request = new Request(url, { method: 'DELETE' });
205
- this.setHeaders(request.headers, headers);
206
- const response = await this.fetchWithRetry(request);
207
- return response;
208
- }
209
-
210
- public async getDocuments<T extends Resource>(
211
- args: GetDocumentsArgs
212
- ): Promise<FeedResponse<T & Document>> {
213
- const { dbId = this.dbId, collId = this.collId, ...headers } = args;
214
- assertArg('dbId', dbId);
215
- assertArg('collId', collId);
216
- const url = this.endpoint + uri`/dbs/${dbId}/colls/${collId}/docs`;
217
- const request = new Request(url, { method: 'GET' });
218
- this.setHeaders(request.headers, headers);
219
- const response = await this.fetchWithRetry(request);
220
- const next = this.getNext<GetDocumentsArgs, T & Document>(
221
- response,
222
- args,
223
- this.getDocuments
224
- );
225
- return new FeedResponse<T & Document>(response, next, 'Documents');
226
- }
227
-
228
- public async getDocument<T extends Resource>(
229
- args: GetDocumentArgs
230
- ): Promise<ItemResponse<T & Document>> {
231
- const { dbId = this.dbId, collId = this.collId, docId, ...headers } = args;
232
- assertArg('dbId', dbId);
233
- assertArg('collId', collId);
234
- const url = this.endpoint + uri`/dbs/${dbId}/colls/${collId}/docs/${docId}`;
235
- const request = new Request(url, { method: 'GET' });
236
- this.setHeaders(request.headers, headers);
237
- const response = await this.fetchWithRetry(request);
238
- return new ItemResponse<T & Document>(response);
239
- }
240
-
241
- public async createDocument<T extends Resource>(
242
- args: CreateDocumentArgs
243
- ): Promise<ItemResponse<T & Document>> {
244
- const {
245
- dbId = this.dbId,
246
- collId = this.collId,
247
- document,
248
- ...headers
249
- } = args;
250
- assertArg('dbId', dbId);
251
- assertArg('collId', collId);
252
- const url = this.endpoint + uri`/dbs/${dbId}/colls/${collId}/docs`;
253
- const body = toBodyInit(document);
254
- const request = new Request(url, { method: 'POST', body });
255
- this.setHeaders(request.headers, headers);
256
- request.headers.set('content-type', 'application/json');
257
- const response = await this.fetchWithRetry(request);
258
- return new ItemResponse<T & Document>(response);
259
- }
260
-
261
- public async replaceDocument<T extends Resource>(
262
- args: ReplaceDocumentArgs
263
- ): Promise<ItemResponse<T & Document>> {
264
- const {
265
- dbId = this.dbId,
266
- collId = this.collId,
267
- docId,
268
- document,
269
- ...headers
270
- } = args;
271
- assertArg('dbId', dbId);
272
- assertArg('collId', collId);
273
- const url = this.endpoint + uri`/dbs/${dbId}/colls/${collId}/docs/${docId}`;
274
- const body = toBodyInit(document);
275
- const request = new Request(url, { method: 'PUT', body });
276
- this.setHeaders(request.headers, headers);
277
- request.headers.set('content-type', 'application/json');
278
- const response = await this.fetchWithRetry(request);
279
- return new ItemResponse<T & Document>(response);
280
- }
281
-
282
- public async deleteDocument(args: DeleteDocumentArgs): Promise<Response> {
283
- const { dbId = this.dbId, collId = this.collId, docId, ...headers } = args;
284
- assertArg('dbId', dbId);
285
- assertArg('collId', collId);
286
- const url = this.endpoint + uri`/dbs/${dbId}/colls/${collId}/docs/${docId}`;
287
- const request = new Request(url, { method: 'DELETE' });
288
- this.setHeaders(request.headers, headers);
289
- const response = await this.fetchWithRetry(request);
290
- return response;
291
- }
292
-
293
- public async queryDocuments<T>(
294
- args: QueryDocumentsArgs
295
- ): Promise<FeedResponse<T>> {
296
- const {
297
- dbId = this.dbId,
298
- collId = this.collId,
299
- query,
300
- parameters = [],
301
- ...headerArgs
302
- } = args;
303
-
304
- assertArg('dbId', dbId);
305
- assertArg('collId', collId);
306
-
307
- const headers = Object.assign(
308
- {
309
- enableCrossPartition: this.enableCrossPartitionQueries,
310
- enableScan: false,
311
- maxItems: -1,
312
- populateMetrics: false,
313
- isQuery: true
314
- },
315
- headerArgs
316
- );
317
- const url = this.endpoint + uri`/dbs/${dbId}/colls/${collId}/docs`;
318
- const body = JSON.stringify({ query, parameters });
319
- const request = new Request(url, { method: 'POST', body });
320
- this.setHeaders(request.headers, headers);
321
- request.headers.set('content-type', 'application/query+json');
322
- const response = await this.fetchWithRetry(request);
323
- const next = this.getNext<QueryDocumentsArgs, T>(
324
- response,
325
- args,
326
- this.queryDocuments
327
- );
328
- return new FeedResponse<T>(response, next, 'Documents');
329
- }
330
-
331
- private getNext<TArgs extends CommonGetListArgs, TResult>(
332
- response: Response,
333
- args: TArgs,
334
- fn: (args: TArgs) => Promise<FeedResponse<TResult>>
335
- ): () => Promise<FeedResponse<TResult>> {
336
- return () => {
337
- const continuation = response.headers.get('x-ms-continuation');
338
- if (!continuation) {
339
- throw new Error(`Response is not continuable.`);
340
- }
341
- return fn.call(this, Object.assign({}, args, { continuation }));
342
- };
343
- }
344
-
345
- private async fetchWithRetry(
346
- request: Request,
347
- context?: RetryContext
348
- ): Promise<Response> {
349
- const retryRequest = request.clone();
350
-
351
- const response = await this.fetch(request);
352
-
353
- context ??= { attempts: 0, cumulativeWaitMs: 0, request, response };
354
- context.attempts++;
355
- context.request = retryRequest;
356
- context.response = response;
357
-
358
- const { retry, delayMs } = await this.retryPolicy.shouldRetry(context);
359
- if (!retry) {
360
- return response;
361
- }
362
- if (delayMs !== 0) {
363
- await new Promise(resolve => setTimeout(resolve, delayMs));
364
- context.cumulativeWaitMs += delayMs;
365
- this.retries.delayMs += delayMs;
366
- }
367
- this.retries.count++;
368
- return this.fetchWithRetry(retryRequest, context);
369
- }
370
-
371
- private async fetch(request: Request): Promise<Response> {
372
- this.sessions.setRequestSession(request);
373
- await this.signer.sign(request);
374
- const response = await this.systemFetch(request);
375
- this.sessions.readResponseSession(response);
376
- const requestCharge = +(response.headers.get('x-ms-request-charge') || 0);
377
- this.requestCharges += requestCharge;
378
- return response;
379
- }
380
-
381
- private setHeaders(headers: Headers, args: AllHeaders) {
382
- headers.set('accept', 'application/json');
383
- headers.set('cache-control', 'no-cache');
384
- headers.set('x-ms-version', '2018-12-31');
385
- if (args.activityId) {
386
- headers.set('x-ms-activity-id', args.activityId);
387
- }
388
- const consistencyLevel = args.consistencyLevel || this.consistencyLevel;
389
- headers.set('x-ms-consistency-level', consistencyLevel);
390
- if (args.continuation) {
391
- headers.set('x-ms-continuation', args.continuation);
392
- }
393
- if (args.enableScan) {
394
- headers.set('x-ms-documentdb-query-enable-scan', 'true');
395
- }
396
- if (args.ifMatch) {
397
- headers.set('if-match', args.ifMatch);
398
- }
399
- if (args.ifModifiedSince) {
400
- headers.set('if-modified-since', args.ifModifiedSince.toUTCString());
401
- }
402
- if (args.ifNoneMatch) {
403
- headers.set('if-none-match', args.ifNoneMatch);
404
- }
405
- if (args.indexingDirective) {
406
- headers.set('x-ms-indexing-directive', args.indexingDirective);
407
- }
408
- if (args.isQuery) {
409
- headers.set('x-ms-documentdb-isquery', args.isQuery.toString());
410
- }
411
- if (args.isUpsert) {
412
- headers.set('x-ms-documentdb-is-upsert', args.isUpsert.toString());
413
- }
414
- if (args.maxItems) {
415
- headers.set('x-ms-max-item-count', args.maxItems.toString(10));
416
- }
417
- if (args.offerType) {
418
- headers.set('x-ms-offer-type', args.offerType);
419
- }
420
- if (args.offerThroughput) {
421
- headers.set('x-ms-offer-throughput', args.offerThroughput.toString());
422
- }
423
- if (args.populateMetrics) {
424
- headers.set('x-ms-documentdb-populatequerymetrics', 'true');
425
- }
426
- if (args.partitionKey) {
427
- headers.set(
428
- 'x-ms-documentdb-partitionkey',
429
- escapeNonASCII(JSON.stringify([args.partitionKey]))
430
- );
431
- if (args.isQuery) {
432
- headers.set('x-ms-documentdb-query-enablecrosspartition', 'false');
433
- }
434
- } else if (args.enableCrossPartition !== undefined && args.isQuery) {
435
- headers.set(
436
- 'x-ms-documentdb-query-enablecrosspartition',
437
- args.enableCrossPartition.toString()
438
- );
439
- }
440
- }
441
- }
442
-
443
- export type DocumentInit = BufferSource | ReadableStream | string | Resource;
444
-
445
- function toBodyInit(obj: DocumentInit): BodyInit {
446
- if (
447
- (typeof obj === 'string' || DataView.prototype.isPrototypeOf(obj),
448
- ArrayBuffer.isView(obj) || obj instanceof ReadableStream)
449
- ) {
450
- return obj as any;
451
- }
452
- return JSON.stringify(obj);
453
- }
454
-
455
- interface CommonArgs {
456
- activityId?: string;
457
- consistencyLevel?: ConsistencyLevel;
458
- }
459
-
460
- interface CommonGetArgs extends CommonArgs {
461
- ifNoneMatch?: string;
462
- ifModifiedSince?: Date;
463
- }
464
-
465
- interface CommonGetListArgs extends CommonGetArgs {
466
- maxItems?: number;
467
- continuation?: string;
468
- }
469
-
470
- export type GetDatabasesArgs = CommonGetListArgs;
471
-
472
- export interface GetDatabaseArgs extends CommonGetArgs {
473
- dbId?: string;
474
- }
475
-
476
- export interface GetCollectionsArgs extends CommonGetListArgs {
477
- dbId?: string;
478
- }
479
-
480
- export interface GetCollectionArgs extends CommonGetArgs {
481
- dbId?: string;
482
- collId?: string;
483
- }
484
-
485
- export interface CreateCollectionArgs extends CommonArgs {
486
- dbId?: string;
487
- collId?: string;
488
- indexingPolicy?: IndexingPolicy;
489
- partitionKey: PartitionKeyDefinition;
490
- offerThroughput?: number;
491
- offerType?: OfferType;
492
- }
493
-
494
- export interface ReplaceCollectionArgs extends CommonArgs {
495
- dbId?: string;
496
- collId?: string;
497
- indexingPolicy: IndexingPolicy;
498
- partitionKey: PartitionKeyDefinition;
499
- ifMatch?: string;
500
- }
501
-
502
- export interface DeleteCollectionArgs extends CommonArgs {
503
- dbId?: string;
504
- collId?: string;
505
- ifMatch?: string;
506
- }
507
-
508
- export interface GetDocumentsArgs extends CommonGetListArgs {
509
- dbId?: string;
510
- collId?: string;
511
- partitionKey?: string;
512
- }
513
-
514
- export interface GetDocumentArgs extends CommonGetArgs {
515
- dbId?: string;
516
- collId?: string;
517
- docId: string;
518
- partitionKey: string;
519
- }
520
-
521
- export interface QueryDocumentsArgs extends CommonGetListArgs {
522
- dbId?: string;
523
- collId?: string;
524
- query: string;
525
- parameters?: QueryParameter[];
526
- partitionKey?: string;
527
- enableCrossPartition?: boolean;
528
- populateMetrics?: boolean;
529
- enableScan?: boolean;
530
- }
531
-
532
- export interface QueryParameter {
533
- name: string;
534
- value: string | number | boolean | null | undefined;
535
- }
536
-
537
- export interface CreateDocumentArgs extends CommonArgs {
538
- dbId?: string;
539
- collId?: string;
540
- document: DocumentInit;
541
- partitionKey: string;
542
- isUpsert?: boolean;
543
- indexingDirective?: IndexingDirective;
544
- }
545
-
546
- export interface ReplaceDocumentArgs extends CommonArgs {
547
- dbId?: string;
548
- collId?: string;
549
- docId: string;
550
- document: DocumentInit;
551
- partitionKey: string;
552
- ifMatch?: string;
553
- indexingDirective?: IndexingDirective;
554
- }
555
-
556
- export interface DeleteDocumentArgs extends CommonArgs {
557
- dbId?: string;
558
- collId?: string;
559
- docId: string;
560
- partitionKey: string;
561
- ifMatch?: string;
562
- }
563
-
564
- interface AllHeaders {
565
- activityId?: string;
566
- consistencyLevel?: ConsistencyLevel;
567
- continuation?: string;
568
- enableCrossPartition?: boolean;
569
- enableScan?: boolean;
570
- ifMatch?: string;
571
- ifModifiedSince?: Date;
572
- ifNoneMatch?: string;
573
- indexingDirective?: IndexingDirective;
574
- isQuery?: boolean;
575
- isUpsert?: boolean;
576
- maxItems?: number;
577
- offerType?: OfferType;
578
- offerThroughput?: number;
579
- partitionKey?: string;
580
- populateMetrics?: boolean;
581
- }
package/src/response.ts DELETED
@@ -1,59 +0,0 @@
1
- import { PersistedResource } from './types.js';
2
-
3
- export abstract class CosmosResponse {
4
- constructor(protected readonly response: Response) {}
5
-
6
- get status(): number {
7
- return this.response.status;
8
- }
9
- get headers(): Headers {
10
- return this.response.headers;
11
- }
12
- get body(): ReadableStream<Uint8Array> | null {
13
- return this.response.body;
14
- }
15
- get activityId(): string | null {
16
- return this.response.headers.get('x-ms-activity-id');
17
- }
18
- get etag(): string {
19
- return this.response.headers.get('etag')!;
20
- }
21
- get requestCharge(): number {
22
- return parseInt(this.response.headers.get('x-ms-request-charge')!);
23
- }
24
- get raw(): Response {
25
- return this.response;
26
- }
27
- }
28
-
29
- export class ItemResponse<T extends PersistedResource> extends CosmosResponse {
30
- constructor(response: Response) {
31
- super(response);
32
- }
33
-
34
- json(): Promise<T> {
35
- return this.response.json();
36
- }
37
- }
38
-
39
- export class FeedResponse<T> extends CosmosResponse {
40
- constructor(
41
- response: Response,
42
- public readonly next: () => Promise<FeedResponse<T>>,
43
- private readonly itemsProperty: string
44
- ) {
45
- super(response);
46
- }
47
-
48
- get count(): number {
49
- return parseInt(this.response.headers.get('x-ms-item-count')!);
50
- }
51
- get hasNext(): boolean {
52
- return this.response.headers.has('x-ms-continuation');
53
- }
54
-
55
- async json(): Promise<T[]> {
56
- const data: any = await this.response.json();
57
- return data[this.itemsProperty];
58
- }
59
- }
package/src/retry.ts DELETED
@@ -1,45 +0,0 @@
1
- import { readSessionNotAvailable } from './session';
2
-
3
- export interface RetryContext {
4
- request: Request;
5
- response: Response;
6
- attempts: number;
7
- cumulativeWaitMs: number;
8
- }
9
-
10
- export interface RetryInstruction {
11
- retry: boolean;
12
- delayMs: number;
13
- }
14
-
15
- export interface RetryPolicy {
16
- shouldRetry(context: RetryContext): Promise<RetryInstruction>;
17
- }
18
-
19
- export class DefaultRetryPolicy implements RetryPolicy {
20
- constructor(
21
- public readonly maxAttempts = 10,
22
- public readonly maxCumulativeWaitTimeMs = 30000,
23
- public readonly defaultRetryDelayMs = 5000
24
- ) {}
25
-
26
- async shouldRetry(context: RetryContext): Promise<RetryInstruction> {
27
- if (readSessionNotAvailable(context.response)) {
28
- return { retry: true, delayMs: 0 };
29
- }
30
- if (
31
- context.response.status !== 429 ||
32
- context.attempts >= this.maxAttempts ||
33
- context.cumulativeWaitMs >= this.maxCumulativeWaitTimeMs
34
- ) {
35
- return { retry: false, delayMs: 0 };
36
- }
37
- const delayMs = +(
38
- context.response.headers.get('x-ms-retry-after-ms') ||
39
- this.defaultRetryDelayMs
40
- );
41
- return { retry: true, delayMs };
42
- }
43
- }
44
-
45
- export const defaultRetryPolicy: RetryPolicy = new DefaultRetryPolicy();