-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
ContainerClient.ts
2167 lines (2058 loc) · 74.5 KB
/
ContainerClient.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { AbortSignalLike } from "@azure/abort-controller";
import {
getDefaultProxySettings,
HttpRequestBody,
HttpResponse,
isNode,
isTokenCredential,
TokenCredential,
URLBuilder,
} from "@azure/core-http";
import { PagedAsyncIterableIterator, PageSettings } from "@azure/core-paging";
import { SpanStatusCode } from "@azure/core-tracing";
import { AnonymousCredential } from "./credentials/AnonymousCredential";
import { StorageSharedKeyCredential } from "./credentials/StorageSharedKeyCredential";
import { Container } from "./generated/src/operations";
import {
BlobDeleteResponse,
BlobPrefix,
BlobProperties,
BlockBlobUploadResponse,
ContainerCreateResponse,
ContainerDeleteResponse,
ContainerEncryptionScope,
ContainerFilterBlobsHeaders,
ContainerGetAccessPolicyHeaders,
ContainerGetPropertiesResponse,
ContainerListBlobFlatSegmentHeaders,
ContainerListBlobHierarchySegmentHeaders,
ContainerSetAccessPolicyResponse,
ContainerSetMetadataResponse,
FilterBlobItem,
FilterBlobSegment,
FilterBlobSegmentModel,
LeaseAccessConditions,
ListBlobsFlatSegmentResponseModel,
ListBlobsHierarchySegmentResponseModel,
PublicAccessType,
SignedIdentifierModel,
} from "./generatedModels";
import {
Metadata,
ObjectReplicationPolicy,
Tags,
ContainerRequestConditions,
ModifiedAccessConditions,
} from "./models";
import { newPipeline, PipelineLike, isPipelineLike, StoragePipelineOptions } from "./Pipeline";
import { CommonOptions, StorageClient } from "./StorageClient";
import { convertTracingToRequestOptionsBase, createSpan } from "./utils/tracing";
import {
appendToURLPath,
appendToURLQuery,
BlobNameToString,
ConvertInternalResponseOfListBlobFlat,
ConvertInternalResponseOfListBlobHierarchy,
extractConnectionStringParts,
isIpEndpointStyle,
parseObjectReplicationRecord,
ProcessBlobItems,
ProcessBlobPrefixes,
toTags,
truncatedISO8061Date,
} from "./utils/utils.common";
import { ContainerSASPermissions } from "./sas/ContainerSASPermissions";
import { generateBlobSASQueryParameters } from "./sas/BlobSASSignatureValues";
import { BlobLeaseClient } from "./BlobLeaseClient";
import {
AppendBlobClient,
BlobClient,
BlobDeleteOptions,
BlockBlobClient,
BlockBlobUploadOptions,
CommonGenerateSasUrlOptions,
PageBlobClient,
} from "./Clients";
import { BlobBatchClient } from "./BlobBatchClient";
import { ListBlobsIncludeItem } from "./generated/src";
/**
* Options to configure {@link ContainerClient.create} operation.
*/
export interface ContainerCreateOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* A collection of key-value string pair to associate with the container.
*/
metadata?: Metadata;
/**
* Specifies whether data in the container may be accessed publicly and the level of access. Possible values include:
* - `container`: Specifies full public read access for container and blob data. Clients can enumerate blobs within the container via anonymous request, but cannot enumerate containers within the storage account.
* - `blob`: Specifies public read access for blobs. Blob data within this container can be read via anonymous request, but container data is not available. Clients cannot enumerate blobs within the container via anonymous request.
*/
access?: PublicAccessType;
/**
* Container encryption scope info.
*/
containerEncryptionScope?: ContainerEncryptionScope;
}
/**
* Options to configure {@link ContainerClient.getProperties} operation.
*/
export interface ContainerGetPropertiesOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* If specified, contains the lease id that must be matched and lease with this id
* must be active in order for the operation to succeed.
*/
conditions?: LeaseAccessConditions;
}
/**
* Options to configure {@link ContainerClient.delete} operation.
*/
export interface ContainerDeleteMethodOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* Conditions to meet when deleting the container.
*/
conditions?: ContainerRequestConditions;
}
/**
* Options to configure {@link ContainerClient.exists} operation.
*/
export interface ContainerExistsOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
}
/**
* Options to configure {@link ContainerClient.setMetadata} operation.
*/
export interface ContainerSetMetadataOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* If specified, contains the lease id that must be matched and lease with this id
* must be active in order for the operation to succeed.
*/
conditions?: ContainerRequestConditions;
}
/**
* Options to configure {@link ContainerClient.getAccessPolicy} operation.
*/
export interface ContainerGetAccessPolicyOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* If specified, contains the lease id that must be matched and lease with this id
* must be active in order for the operation to succeed.
*/
conditions?: LeaseAccessConditions;
}
/**
* Signed identifier.
*/
export interface SignedIdentifier {
/**
* a unique id
*/
id: string;
/**
* Access Policy
*/
accessPolicy: {
/**
* Optional. The date-time the policy is active
*/
startsOn?: Date;
/**
* Optional. The date-time the policy expires
*/
expiresOn?: Date;
/**
* The permissions for the acl policy
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl
*/
permissions?: string;
};
}
/**
* Contains response data for the {@link ContainerClient.getAccessPolicy} operation.
*/
export declare type ContainerGetAccessPolicyResponse = {
signedIdentifiers: SignedIdentifier[];
} & ContainerGetAccessPolicyHeaders & {
/**
* The underlying HTTP response.
*/
_response: HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: ContainerGetAccessPolicyHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SignedIdentifierModel[];
};
};
/**
* Options to configure {@link ContainerClient.setAccessPolicy} operation.
*/
export interface ContainerSetAccessPolicyOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* Conditions to meet when setting the access policy.
*/
conditions?: ContainerRequestConditions;
}
/**
* Options to configure Container - Acquire Lease operation.
*/
export interface ContainerAcquireLeaseOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* Conditions to meet when acquiring the lease.
*/
conditions?: ModifiedAccessConditions;
}
/**
* Options to configure Container - Release Lease operation.
*/
export interface ContainerReleaseLeaseOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* Conditions to meet when releasing the lease.
*/
conditions?: ModifiedAccessConditions;
}
/**
* Options to configure Container - Renew Lease operation.
*/
export interface ContainerRenewLeaseOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* Conditions to meet when renewing the lease.
*/
conditions?: ModifiedAccessConditions;
}
/**
* Options to configure Container - Break Lease operation.
*/
export interface ContainerBreakLeaseOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* Conditions to meet when breaking the lease.
*/
conditions?: ModifiedAccessConditions;
}
/**
* Options to configure Container - Change Lease operation.
*/
export interface ContainerChangeLeaseOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* Conditions to meet when changing the lease.
*/
conditions?: ModifiedAccessConditions;
}
/**
* Options to configure the {@link ContainerClient.deleteBlob} operation.
*/
export interface ContainerDeleteBlobOptions extends BlobDeleteOptions {
/**
* An opaque DateTime value that, when present, specifies the version
* of the blob to delete. It's for service version 2019-10-10 and newer.
*/
versionId?: string;
}
/**
* Options to configure Container - List Segment operations.
*
* See:
* - {@link ContainerClient.listSegments}
* - {@link ContainerClient.listBlobFlatSegment}
* - {@link ContainerClient.listBlobHierarchySegment}
* - {@link ContainerClient.listHierarchySegments}
* - {@link ContainerClient.listItemsByHierarchy}
*/
interface ContainerListBlobsSegmentOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* Filters the results to return only containers
* whose name begins with the specified prefix.
*/
prefix?: string;
/**
* Specifies the maximum number of containers
* to return. If the request does not specify maxPageSize, or specifies a
* value greater than 5000, the server will return up to 5000 items. Note
* that if the listing operation crosses a partition boundary, then the
* service will return a continuation token for retrieving the remainder of
* the results. For this reason, it is possible that the service will return
* fewer results than specified by maxPageSize, or than the default of 5000.
*/
maxPageSize?: number;
/**
* Include this parameter to
* specify one or more datasets to include in the response.
*/
include?: ListBlobsIncludeItem[];
}
/**
* An interface representing BlobHierarchyListSegment.
*/
export interface BlobHierarchyListSegment {
blobPrefixes?: BlobPrefix[];
blobItems: BlobItem[];
}
/**
* An enumeration of blobs
*/
export interface ListBlobsHierarchySegmentResponse {
serviceEndpoint: string;
containerName: string;
prefix?: string;
marker?: string;
maxPageSize?: number;
delimiter?: string;
segment: BlobHierarchyListSegment;
continuationToken?: string;
}
/**
* Contains response data for the listBlobHierarchySegment operation.
*/
export type ContainerListBlobHierarchySegmentResponse = ListBlobsHierarchySegmentResponse &
ContainerListBlobHierarchySegmentHeaders & {
/**
* The underlying HTTP response.
*/
_response: HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: ContainerListBlobHierarchySegmentHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ListBlobsHierarchySegmentResponseModel;
};
};
/**
* An Azure Storage blob
*/
export interface BlobItem {
name: string;
deleted: boolean;
snapshot: string;
versionId?: string;
isCurrentVersion?: boolean;
properties: BlobProperties;
metadata?: { [propertyName: string]: string };
tags?: Tags;
objectReplicationSourceProperties?: ObjectReplicationPolicy[];
hasVersionsOnly?: boolean;
}
/**
* An interface representing BlobFlatListSegment.
*/
export interface BlobFlatListSegment {
blobItems: BlobItem[];
}
/**
* An enumeration of blobs
*/
export interface ListBlobsFlatSegmentResponse {
serviceEndpoint: string;
containerName: string;
prefix?: string;
marker?: string;
maxPageSize?: number;
segment: BlobFlatListSegment;
continuationToken?: string;
}
/**
* Contains response data for the listBlobFlatSegment operation.
*/
export type ContainerListBlobFlatSegmentResponse = ListBlobsFlatSegmentResponse &
ContainerListBlobFlatSegmentHeaders & {
/**
* The underlying HTTP response.
*/
_response: HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: ContainerListBlobFlatSegmentHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ListBlobsFlatSegmentResponseModel;
};
};
/**
* Options to configure Container - List Blobs operations.
*
* See:
* - {@link ContainerClient.listBlobsFlat}
* - {@link ContainerClient.listBlobsByHierarchy}
*/
export interface ContainerListBlobsOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* Filters the results to return only containers
* whose name begins with the specified prefix.
*/
prefix?: string;
/**
* Specifies whether metadata related to any current or previous Copy Blob operation should be included in the response.
*/
includeCopy?: boolean;
/**
* Specifies whether soft deleted blobs should be included in the response.
*/
includeDeleted?: boolean;
/**
* Specifies whether blob metadata be returned in the response.
*/
includeMetadata?: boolean;
/**
* Specifies whether snapshots should be included in the enumeration. Snapshots are listed from oldest to newest in the response.
*/
includeSnapshots?: boolean;
/**
* Specifies whether versions should be included in the enumeration. Versions are listed from oldest to newest in the response.
*/
includeVersions?: boolean;
/**
* Specifies whether blobs for which blocks have been uploaded, but which have not been committed using Put Block List, be included in the response.
*/
includeUncommitedBlobs?: boolean;
/**
* Specifies whether blob tags be returned in the response.
*/
includeTags?: boolean;
/**
* Specifies whether deleted blob with versions be returned in the response.
*/
includeDeletedWithVersions?: boolean;
/**
* Specifies whether blob immutability policy be returned in the response.
*/
includeImmutabilityPolicy?: boolean;
/**
* Specifies whether blob legal hold be returned in the response.
*/
includeLegalHold?: boolean;
}
/**
* Contains response data for the {@link ContainerClient.createIfNotExists} operation.
*/
export interface ContainerCreateIfNotExistsResponse extends ContainerCreateResponse {
/**
* Indicate whether the container is successfully created. Is false when the container is not changed as it already exists.
*/
succeeded: boolean;
}
/**
* Contains response data for the {@link ContainerClient.deleteIfExists} operation.
*/
export interface ContainerDeleteIfExistsResponse extends ContainerDeleteResponse {
/**
* Indicate whether the container is successfully deleted. Is false if the container does not exist in the first place.
*/
succeeded: boolean;
}
/**
* Options to configure {@link ContainerClient.generateSasUrl} operation.
*/
export interface ContainerGenerateSasUrlOptions extends CommonGenerateSasUrlOptions {
/**
* Optional only when identifier is provided. Specifies the list of permissions to be associated with the SAS.
*/
permissions?: ContainerSASPermissions;
}
/**
* Options to configure the {@link ContainerClient.findBlobsByTagsSegment} operation.
*/
interface ContainerFindBlobsByTagsSegmentOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
/**
* Specifies the maximum number of blobs
* to return. If the request does not specify maxPageSize, or specifies a
* value greater than 5000, the server will return up to 5000 items. Note
* that if the listing operation crosses a partition boundary, then the
* service will return a continuation token for retrieving the remainder of
* the results. For this reason, it is possible that the service will return
* fewer results than specified by maxPageSize, or than the default of 5000.
*/
maxPageSize?: number;
}
/**
* Options to configure the {@link BlobServiceClient.findBlobsByTags} operation.
*/
export interface ContainerFindBlobByTagsOptions extends CommonOptions {
/**
* An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.
* For example, use the @azure/abort-controller to create an `AbortSignal`.
*/
abortSignal?: AbortSignalLike;
}
/**
* The response of {@link BlobServiceClient.findBlobsByTags} operation.
*/
export type ContainerFindBlobsByTagsSegmentResponse = FilterBlobSegment &
ContainerFilterBlobsHeaders & {
/**
* The underlying HTTP response.
*/
_response: HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: ContainerFilterBlobsHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: FilterBlobSegmentModel;
};
};
/**
* A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs.
*/
export class ContainerClient extends StorageClient {
/**
* containerContext provided by protocol layer.
*/
private containerContext: Container;
private _containerName: string;
/**
* The name of the container.
*/
public get containerName(): string {
return this._containerName;
}
/**
*
* Creates an instance of ContainerClient.
*
* @param connectionString - Account connection string or a SAS connection string of an Azure storage account.
* [ Note - Account connection string can only be used in NODE.JS runtime. ]
* Account connection string example -
* `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net`
* SAS connection string example -
* `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString`
* @param containerName - Container name.
* @param options - Optional. Options to configure the HTTP pipeline.
*/
// Legacy, no fix for eslint error without breaking. Disable it for this interface.
/* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/
constructor(connectionString: string, containerName: string, options?: StoragePipelineOptions);
/**
* Creates an instance of ContainerClient.
* This method accepts an URL pointing to a container.
* Encoded URL string will NOT be escaped twice, only special characters in URL path will be escaped.
* If a blob name includes ? or %, blob name must be encoded in the URL.
*
* @param url - A URL string pointing to Azure Storage container, such as
* "https://myaccount.blob.core.windows.net/mycontainer". You can
* append a SAS if using AnonymousCredential, such as
* "https://myaccount.blob.core.windows.net/mycontainer?sasString".
* @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used.
* @param options - Optional. Options to configure the HTTP pipeline.
*/
constructor(
url: string,
credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential,
// Legacy, no fix for eslint error without breaking. Disable it for this interface.
/* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/
options?: StoragePipelineOptions
);
/**
* Creates an instance of ContainerClient.
* This method accepts an URL pointing to a container.
* Encoded URL string will NOT be escaped twice, only special characters in URL path will be escaped.
* If a blob name includes ? or %, blob name must be encoded in the URL.
*
* @param url - A URL string pointing to Azure Storage container, such as
* "https://myaccount.blob.core.windows.net/mycontainer". You can
* append a SAS if using AnonymousCredential, such as
* "https://myaccount.blob.core.windows.net/mycontainer?sasString".
* @param pipeline - Call newPipeline() to create a default
* pipeline, or provide a customized pipeline.
*/
constructor(url: string, pipeline: PipelineLike);
constructor(
urlOrConnectionString: string,
credentialOrPipelineOrContainerName?:
| string
| StorageSharedKeyCredential
| AnonymousCredential
| TokenCredential
| PipelineLike,
// Legacy, no fix for eslint error without breaking. Disable it for this interface.
/* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/
options?: StoragePipelineOptions
) {
let pipeline: PipelineLike;
let url: string;
options = options || {};
if (isPipelineLike(credentialOrPipelineOrContainerName)) {
// (url: string, pipeline: Pipeline)
url = urlOrConnectionString;
pipeline = credentialOrPipelineOrContainerName;
} else if (
(isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) ||
credentialOrPipelineOrContainerName instanceof AnonymousCredential ||
isTokenCredential(credentialOrPipelineOrContainerName)
) {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
url = urlOrConnectionString;
pipeline = newPipeline(credentialOrPipelineOrContainerName, options);
} else if (
!credentialOrPipelineOrContainerName &&
typeof credentialOrPipelineOrContainerName !== "string"
) {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
// The second parameter is undefined. Use anonymous credential.
url = urlOrConnectionString;
pipeline = newPipeline(new AnonymousCredential(), options);
} else if (
credentialOrPipelineOrContainerName &&
typeof credentialOrPipelineOrContainerName === "string"
) {
// (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions)
const containerName = credentialOrPipelineOrContainerName;
const extractedCreds = extractConnectionStringParts(urlOrConnectionString);
if (extractedCreds.kind === "AccountConnString") {
if (isNode) {
const sharedKeyCredential = new StorageSharedKeyCredential(
extractedCreds.accountName!,
extractedCreds.accountKey
);
url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName));
if (!options.proxyOptions) {
options.proxyOptions = getDefaultProxySettings(extractedCreds.proxyUri);
}
pipeline = newPipeline(sharedKeyCredential, options);
} else {
throw new Error("Account connection string is only supported in Node.js environment");
}
} else if (extractedCreds.kind === "SASConnString") {
url =
appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) +
"?" +
extractedCreds.accountSas;
pipeline = newPipeline(new AnonymousCredential(), options);
} else {
throw new Error(
"Connection string must be either an Account connection string or a SAS connection string"
);
}
} else {
throw new Error("Expecting non-empty strings for containerName parameter");
}
super(url, pipeline);
this._containerName = this.getContainerNameFromUrl();
this.containerContext = new Container(this.storageClientContext);
}
/**
* Creates a new container under the specified account. If the container with
* the same name already exists, the operation fails.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container
*
* @param options - Options to Container Create operation.
*
*
* Example usage:
*
* ```js
* const containerClient = blobServiceClient.getContainerClient("<container name>");
* const createContainerResponse = await containerClient.create();
* console.log("Container was created successfully", createContainerResponse.requestId);
* ```
*/
public async create(options: ContainerCreateOptions = {}): Promise<ContainerCreateResponse> {
const { span, updatedOptions } = createSpan("ContainerClient-create", options);
try {
// Spread operator in destructuring assignments,
// this will filter out unwanted properties from the response object into result object
return await this.containerContext.create({
...options,
...convertTracingToRequestOptionsBase(updatedOptions),
});
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message,
});
throw e;
} finally {
span.end();
}
}
/**
* Creates a new container under the specified account. If the container with
* the same name already exists, it is not changed.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container
*
* @param options -
*/
public async createIfNotExists(
options: ContainerCreateOptions = {}
): Promise<ContainerCreateIfNotExistsResponse> {
const { span, updatedOptions } = createSpan("ContainerClient-createIfNotExists", options);
try {
const res = await this.create(updatedOptions);
return {
succeeded: true,
...res,
_response: res._response, // _response is made non-enumerable
};
} catch (e: any) {
if (e.details?.errorCode === "ContainerAlreadyExists") {
span.setStatus({
code: SpanStatusCode.ERROR,
message:
"Expected exception when creating a container only if it does not already exist.",
});
return {
succeeded: false,
...e.response?.parsedHeaders,
_response: e.response,
};
}
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message,
});
throw e;
} finally {
span.end();
}
}
/**
* Returns true if the Azure container resource represented by this client exists; false otherwise.
*
* NOTE: use this function with care since an existing container might be deleted by other clients or
* applications. Vice versa new containers with the same name might be added by other clients or
* applications after this function completes.
*
* @param options -
*/
public async exists(options: ContainerExistsOptions = {}): Promise<boolean> {
const { span, updatedOptions } = createSpan("ContainerClient-exists", options);
try {
await this.getProperties({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
});
return true;
} catch (e: any) {
if (e.statusCode === 404) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: "Expected exception when checking container existence",
});
return false;
}
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message,
});
throw e;
} finally {
span.end();
}
}
/**
* Creates a {@link BlobClient}
*
* @param blobName - A blob name
* @returns A new BlobClient object for the given blob name.
*/
public getBlobClient(blobName: string): BlobClient {
return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline);
}
/**
* Creates an {@link AppendBlobClient}
*
* @param blobName - An append blob name
*/
public getAppendBlobClient(blobName: string): AppendBlobClient {
return new AppendBlobClient(
appendToURLPath(this.url, encodeURIComponent(blobName)),
this.pipeline
);
}
/**
* Creates a {@link BlockBlobClient}
*
* @param blobName - A block blob name
*
*
* Example usage:
*
* ```js
* const content = "Hello world!";
*
* const blockBlobClient = containerClient.getBlockBlobClient("<blob name>");
* const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
* ```
*/
public getBlockBlobClient(blobName: string): BlockBlobClient {
return new BlockBlobClient(
appendToURLPath(this.url, encodeURIComponent(blobName)),
this.pipeline
);
}
/**
* Creates a {@link PageBlobClient}
*
* @param blobName - A page blob name
*/
public getPageBlobClient(blobName: string): PageBlobClient {
return new PageBlobClient(
appendToURLPath(this.url, encodeURIComponent(blobName)),
this.pipeline
);
}
/**
* Returns all user-defined metadata and system properties for the specified
* container. The data returned does not include the container's list of blobs.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties
*
* WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if
* they originally contained uppercase characters. This differs from the metadata keys returned by
* the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which
* will retain their original casing.
*
* @param options - Options to Container Get Properties operation.
*/
public async getProperties(
options: ContainerGetPropertiesOptions = {}
): Promise<ContainerGetPropertiesResponse> {
if (!options.conditions) {
options.conditions = {};
}
const { span, updatedOptions } = createSpan("ContainerClient-getProperties", options);
try {
return await this.containerContext.getProperties({
abortSignal: options.abortSignal,
...options.conditions,
...convertTracingToRequestOptionsBase(updatedOptions),
});
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message,
});
throw e;
} finally {
span.end();
}
}
/**
* Marks the specified container for deletion. The container and any blobs
* contained within it are later deleted during garbage collection.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container
*
* @param options - Options to Container Delete operation.
*/
public async delete(
options: ContainerDeleteMethodOptions = {}
): Promise<ContainerDeleteResponse> {
if (!options.conditions) {
options.conditions = {};
}
const { span, updatedOptions } = createSpan("ContainerClient-delete", options);
try {
return await this.containerContext.delete({
abortSignal: options.abortSignal,
leaseAccessConditions: options.conditions,