-
Notifications
You must be signed in to change notification settings - Fork 369
/
bucket.ts
4551 lines (4312 loc) · 147 KB
/
bucket.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 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
ApiError,
BodyResponseCallback,
DecorateRequestOptions,
DeleteCallback,
ExistsCallback,
GetConfig,
MetadataCallback,
ServiceObject,
SetMetadataResponse,
util,
} from './nodejs-common/index.js';
import {RequestResponse} from './nodejs-common/service-object.js';
import {paginator} from '@google-cloud/paginator';
import {promisifyAll} from '@google-cloud/promisify';
import * as fs from 'fs';
import * as http from 'http';
import mime from 'mime';
import * as path from 'path';
import pLimit from 'p-limit';
import {promisify} from 'util';
import AsyncRetry from 'async-retry';
import {convertObjKeysToSnakeCase} from './util.js';
import {Acl, AclMetadata} from './acl.js';
import {Channel} from './channel.js';
import {
File,
FileOptions,
CreateResumableUploadOptions,
CreateWriteStreamOptions,
FileMetadata,
} from './file.js';
import {Iam} from './iam.js';
import {Notification, NotificationMetadata} from './notification.js';
import {
Storage,
Cors,
PreconditionOptions,
IdempotencyStrategy,
BucketOptions,
} from './storage.js';
import {
GetSignedUrlResponse,
GetSignedUrlCallback,
SignerGetSignedUrlConfig,
URLSigner,
Query,
} from './signer.js';
import {Readable} from 'stream';
import {CRC32CValidatorGenerator} from './crc32c.js';
import {URL} from 'url';
import {
BaseMetadata,
SetMetadataOptions,
} from './nodejs-common/service-object.js';
interface SourceObject {
name: string;
generation?: number;
}
interface CreateNotificationQuery {
userProject?: string;
}
interface MetadataOptions {
predefinedAcl: string;
userProject?: string;
ifGenerationMatch?: number | string;
ifGenerationNotMatch?: number | string;
ifMetagenerationMatch?: number | string;
ifMetagenerationNotMatch?: number | string;
}
export type GetFilesResponse = [File[], {}, unknown];
export interface GetFilesCallback {
(
err: Error | null,
files?: File[],
nextQuery?: {},
apiResponse?: unknown
): void;
}
interface WatchAllOptions {
delimiter?: string;
maxResults?: number;
pageToken?: string;
prefix?: string;
projection?: string;
userProject?: string;
versions?: boolean;
}
export interface AddLifecycleRuleOptions extends PreconditionOptions {
append?: boolean;
}
export interface LifecycleAction {
type: 'Delete' | 'SetStorageClass' | 'AbortIncompleteMultipartUpload';
storageClass?: string;
}
export interface LifecycleCondition {
age?: number;
createdBefore?: Date | string;
customTimeBefore?: Date | string;
daysSinceCustomTime?: number;
daysSinceNoncurrentTime?: number;
isLive?: boolean;
matchesPrefix?: string[];
matchesSuffix?: string[];
matchesStorageClass?: string[];
noncurrentTimeBefore?: Date | string;
numNewerVersions?: number;
}
export interface LifecycleRule {
action: LifecycleAction;
condition: LifecycleCondition;
}
export interface LifecycleCondition {
age?: number;
createdBefore?: Date | string;
customTimeBefore?: Date | string;
daysSinceCustomTime?: number;
daysSinceNoncurrentTime?: number;
isLive?: boolean;
matchesPrefix?: string[];
matchesSuffix?: string[];
matchesStorageClass?: string[];
noncurrentTimeBefore?: Date | string;
numNewerVersions?: number;
}
export interface LifecycleRule {
action: LifecycleAction;
condition: LifecycleCondition;
}
export interface EnableLoggingOptions extends PreconditionOptions {
bucket?: string | Bucket;
prefix: string;
}
export interface GetFilesOptions {
autoPaginate?: boolean;
delimiter?: string;
endOffset?: string;
includeFoldersAsPrefixes?: boolean;
includeTrailingDelimiter?: boolean;
prefix?: string;
matchGlob?: string;
maxApiCalls?: number;
maxResults?: number;
pageToken?: string;
softDeleted?: boolean;
startOffset?: string;
userProject?: string;
versions?: boolean;
}
export interface CombineOptions extends PreconditionOptions {
kmsKeyName?: string;
userProject?: string;
}
export interface CombineCallback {
(err: Error | null, newFile: File | null, apiResponse: unknown): void;
}
export type CombineResponse = [File, unknown];
export interface CreateChannelConfig extends WatchAllOptions {
address: string;
}
export interface CreateChannelOptions {
userProject?: string;
}
export type CreateChannelResponse = [Channel, unknown];
export interface CreateChannelCallback {
(err: Error | null, channel: Channel | null, apiResponse: unknown): void;
}
export interface CreateNotificationOptions {
customAttributes?: {[key: string]: string};
eventTypes?: string[];
objectNamePrefix?: string;
payloadFormat?: string;
userProject?: string;
}
export interface CreateNotificationCallback {
(
err: Error | null,
notification: Notification | null,
apiResponse: unknown
): void;
}
export type CreateNotificationResponse = [Notification, unknown];
export interface DeleteBucketOptions {
ignoreNotFound?: boolean;
userProject?: string;
}
export type DeleteBucketResponse = [unknown];
export interface DeleteBucketCallback extends DeleteCallback {
(err: Error | null, apiResponse: unknown): void;
}
export interface DeleteFilesOptions
extends GetFilesOptions,
PreconditionOptions {
force?: boolean;
}
export interface DeleteFilesCallback {
(err: Error | Error[] | null, apiResponse?: object): void;
}
export type DeleteLabelsResponse = [unknown];
export type DeleteLabelsCallback = SetLabelsCallback;
export type DeleteLabelsOptions = PreconditionOptions;
export type DisableRequesterPaysOptions = PreconditionOptions;
export type DisableRequesterPaysResponse = [unknown];
export interface DisableRequesterPaysCallback {
(err?: Error | null, apiResponse?: object): void;
}
export type EnableRequesterPaysResponse = [unknown];
export interface EnableRequesterPaysCallback {
(err?: Error | null, apiResponse?: unknown): void;
}
export type EnableRequesterPaysOptions = PreconditionOptions;
export interface BucketExistsOptions extends GetConfig {
userProject?: string;
}
export type BucketExistsResponse = [boolean];
export type BucketExistsCallback = ExistsCallback;
export interface GetBucketOptions extends GetConfig {
userProject?: string;
}
export type GetBucketResponse = [Bucket, unknown];
export interface GetBucketCallback {
(err: ApiError | null, bucket: Bucket | null, apiResponse: unknown): void;
}
export interface GetLabelsOptions {
userProject?: string;
}
export type GetLabelsResponse = [unknown];
export interface GetLabelsCallback {
(err: Error | null, labels: object | null): void;
}
export interface BucketMetadata extends BaseMetadata {
acl?: AclMetadata[] | null;
autoclass?: {
enabled?: boolean;
toggleTime?: string;
terminalStorageClass?: string;
terminalStorageClassUpdateTime?: string;
};
billing?: {
requesterPays?: boolean;
};
cors?: Cors[];
customPlacementConfig?: {
dataLocations?: string[];
};
defaultEventBasedHold?: boolean;
defaultObjectAcl?: AclMetadata[];
encryption?: {
defaultKmsKeyName?: string;
} | null;
hierarchicalNamespace?: {
enabled?: boolean;
};
iamConfiguration?: {
publicAccessPrevention?: string;
uniformBucketLevelAccess?: {
enabled?: boolean;
lockedTime?: string;
};
};
labels?: {
[key: string]: string | null;
};
lifecycle?: {
rule?: LifecycleRule[];
} | null;
location?: string;
locationType?: string;
logging?: {
logBucket?: string;
logObjectPrefix?: string;
};
metageneration?: string;
name?: string;
objectRetention?: {
mode?: string;
};
owner?: {
entity?: string;
entityId?: string;
};
projectNumber?: string | number;
retentionPolicy?: {
effectiveTime?: string;
isLocked?: boolean;
retentionPeriod?: string | number;
} | null;
rpo?: string;
softDeletePolicy?: {
retentionDurationSeconds?: string | number;
readonly effectiveTime?: string;
};
storageClass?: string;
timeCreated?: string;
updated?: string;
versioning?: {
enabled?: boolean;
};
website?: {
mainPageSuffix?: string;
notFoundPage?: string;
};
}
export type GetBucketMetadataResponse = [BucketMetadata, unknown];
export interface GetBucketMetadataCallback {
(
err: ApiError | null,
metadata: BucketMetadata | null,
apiResponse: unknown
): void;
}
export interface GetBucketMetadataOptions {
userProject?: string;
}
export interface GetBucketSignedUrlConfig
extends Pick<SignerGetSignedUrlConfig, 'host' | 'signingEndpoint'> {
action: 'list';
version?: 'v2' | 'v4';
cname?: string;
virtualHostedStyle?: boolean;
expires: string | number | Date;
extensionHeaders?: http.OutgoingHttpHeaders;
queryParams?: Query;
}
export enum BucketActionToHTTPMethod {
list = 'GET',
}
export enum AvailableServiceObjectMethods {
setMetadata,
delete,
}
export interface GetNotificationsOptions {
userProject?: string;
}
export interface GetNotificationsCallback {
(
err: Error | null,
notifications: Notification[] | null,
apiResponse: unknown
): void;
}
export type GetNotificationsResponse = [Notification[], unknown];
export interface MakeBucketPrivateOptions {
includeFiles?: boolean;
force?: boolean;
metadata?: BucketMetadata;
userProject?: string;
preconditionOpts?: PreconditionOptions;
}
interface MakeBucketPrivateRequest extends MakeBucketPrivateOptions {
private?: boolean;
}
export type MakeBucketPrivateResponse = [File[]];
export interface MakeBucketPrivateCallback {
(err?: Error | null, files?: File[]): void;
}
export interface MakeBucketPublicOptions {
includeFiles?: boolean;
force?: boolean;
}
export interface MakeBucketPublicCallback {
(err?: Error | null, files?: File[]): void;
}
export type MakeBucketPublicResponse = [File[]];
export interface SetBucketMetadataOptions extends PreconditionOptions {
userProject?: string;
}
export type SetBucketMetadataResponse = [BucketMetadata];
export interface SetBucketMetadataCallback {
(err?: Error | null, metadata?: BucketMetadata): void;
}
export interface BucketLockCallback {
(err?: Error | null, apiResponse?: unknown): void;
}
export type BucketLockResponse = [unknown];
export interface Labels {
[key: string]: string;
}
export interface SetLabelsOptions extends PreconditionOptions {
userProject?: string;
}
export type SetLabelsResponse = [unknown];
export interface SetLabelsCallback {
(err?: Error | null, metadata?: unknown): void;
}
export interface SetBucketStorageClassOptions extends PreconditionOptions {
userProject?: string;
}
export interface SetBucketStorageClassCallback {
(err?: Error | null): void;
}
export type UploadResponse = [File, unknown];
export interface UploadCallback {
(err: Error | null, file?: File | null, apiResponse?: unknown): void;
}
export interface UploadOptions
extends CreateResumableUploadOptions,
CreateWriteStreamOptions {
destination?: string | File;
encryptionKey?: string | Buffer;
kmsKeyName?: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onUploadProgress?: (progressEvent: any) => void;
}
export interface MakeAllFilesPublicPrivateOptions {
force?: boolean;
private?: boolean;
public?: boolean;
userProject?: string;
}
interface MakeAllFilesPublicPrivateCallback {
(err?: Error | Error[] | null, files?: File[]): void;
}
type MakeAllFilesPublicPrivateResponse = [File[]];
export enum BucketExceptionMessages {
PROVIDE_SOURCE_FILE = 'You must provide at least one source file.',
DESTINATION_FILE_NOT_SPECIFIED = 'A destination file must be specified.',
CHANNEL_ID_REQUIRED = 'An ID is required to create a channel.',
TOPIC_NAME_REQUIRED = 'A valid topic name is required.',
CONFIGURATION_OBJECT_PREFIX_REQUIRED = 'A configuration object with a prefix is required.',
SPECIFY_FILE_NAME = 'A file name must be specified.',
METAGENERATION_NOT_PROVIDED = 'A metageneration must be provided.',
SUPPLY_NOTIFICATION_ID = 'You must supply a notification ID.',
}
/**
* @callback Crc32cGeneratorToStringCallback
* A method returning the CRC32C as a base64-encoded string.
*
* @returns {string}
*
* @example
* Hashing the string 'data' should return 'rth90Q=='
*
* ```js
* const buffer = Buffer.from('data');
* crc32c.update(buffer);
* crc32c.toString(); // 'rth90Q=='
* ```
**/
/**
* @callback Crc32cGeneratorValidateCallback
* A method validating a base64-encoded CRC32C string.
*
* @param {string} [value] base64-encoded CRC32C string to validate
* @returns {boolean}
*
* @example
* Should return `true` if the value matches, `false` otherwise
*
* ```js
* const buffer = Buffer.from('data');
* crc32c.update(buffer);
* crc32c.validate('DkjKuA=='); // false
* crc32c.validate('rth90Q=='); // true
* ```
**/
/**
* @callback Crc32cGeneratorUpdateCallback
* A method for passing `Buffer`s for CRC32C generation.
*
* @param {Buffer} [data] data to update CRC32C value with
* @returns {undefined}
*
* @example
* Hashing buffers from 'some ' and 'text\n'
*
* ```js
* const buffer1 = Buffer.from('some ');
* crc32c.update(buffer1);
*
* const buffer2 = Buffer.from('text\n');
* crc32c.update(buffer2);
*
* crc32c.toString(); // 'DkjKuA=='
* ```
**/
/**
* @typedef {object} CRC32CValidator
* @property {Crc32cGeneratorToStringCallback}
* @property {Crc32cGeneratorValidateCallback}
* @property {Crc32cGeneratorUpdateCallback}
*/
/**
* A function that generates a CRC32C Validator. Defaults to {@link CRC32C}
*
* @name Bucket#crc32cGenerator
* @type {CRC32CValidator}
*/
/**
* Get and set IAM policies for your bucket.
*
* @name Bucket#iam
* @mixes Iam
*
* See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management}
* See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access}
* See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles}
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
*
* //-
* // Get the IAM policy for your bucket.
* //-
* bucket.iam.getPolicy(function(err, policy) {
* console.log(policy);
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.iam.getPolicy().then(function(data) {
* const policy = data[0];
* const apiResponse = data[1];
* });
*
* ```
* @example <caption>include:samples/iam.js</caption>
* region_tag:storage_view_bucket_iam_members
* Example of retrieving a bucket's IAM policy:
*
* @example <caption>include:samples/iam.js</caption>
* region_tag:storage_add_bucket_iam_member
* Example of adding to a bucket's IAM policy:
*
* @example <caption>include:samples/iam.js</caption>
* region_tag:storage_remove_bucket_iam_member
* Example of removing from a bucket's IAM policy:
*/
/**
* Cloud Storage uses access control lists (ACLs) to manage object and
* bucket access. ACLs are the mechanism you use to share objects with other
* users and allow other users to access your buckets and objects.
*
* An ACL consists of one or more entries, where each entry grants permissions
* to an entity. Permissions define the actions that can be performed against
* an object or bucket (for example, `READ` or `WRITE`); the entity defines
* who the permission applies to (for example, a specific user or group of
* users).
*
* The `acl` object on a Bucket instance provides methods to get you a list of
* the ACLs defined on your bucket, as well as set, update, and delete them.
*
* Buckets also have
* {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs}
* for all created files. Default ACLs specify permissions that all new
* objects added to the bucket will inherit by default. You can add, delete,
* get, and update entities and permissions for these as well with
* {@link Bucket#acl.default}.
*
* See {@link http://goo.gl/6qBBPO| About Access Control Lists}
* See {@link https://cloud.google.com/storage/docs/access-control/lists#default| Default ACLs}
*
* @name Bucket#acl
* @mixes Acl
* @property {Acl} default Cloud Storage Buckets have
* {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs}
* for all created files. You can add, delete, get, and update entities and
* permissions for these as well. The method signatures and examples are all
* the same, after only prefixing the method call with `default`.
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
*
* //-
* // Make a bucket's contents publicly readable.
* //-
* const myBucket = storage.bucket('my-bucket');
*
* const options = {
* entity: 'allUsers',
* role: storage.acl.READER_ROLE
* };
*
* myBucket.acl.add(options, function(err, aclObject) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* myBucket.acl.add(options).then(function(data) {
* const aclObject = data[0];
* const apiResponse = data[1];
* });
*
* ```
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_print_bucket_acl
* Example of printing a bucket's ACL:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_print_bucket_acl_for_user
* Example of printing a bucket's ACL for a specific user:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_add_bucket_owner
* Example of adding an owner to a bucket:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_remove_bucket_owner
* Example of removing an owner from a bucket:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_add_bucket_default_owner
* Example of adding a default owner to a bucket:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_remove_bucket_default_owner
* Example of removing a default owner from a bucket:
*/
/**
* The API-formatted resource description of the bucket.
*
* Note: This is not guaranteed to be up-to-date when accessed. To get the
* latest record, call the `getMetadata()` method.
*
* @name Bucket#metadata
* @type {object}
*/
/**
* The bucket's name.
* @name Bucket#name
* @type {string}
*/
/**
* Get {@link File} objects for the files currently in the bucket as a
* readable object stream.
*
* @method Bucket#getFilesStream
* @param {GetFilesOptions} [query] Query object for listing files.
* @returns {ReadableStream} A readable stream that emits {@link File} instances.
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
*
* bucket.getFilesStream()
* .on('error', console.error)
* .on('data', function(file) {
* // file is a File object.
* })
* .on('end', function() {
* // All files retrieved.
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* bucket.getFilesStream()
* .on('data', function(file) {
* this.end();
* });
*
* //-
* // If you're filtering files with a delimiter, you should use
* // {@link Bucket#getFiles} and set `autoPaginate: false` in order to
* // preserve the `apiResponse` argument.
* //-
* const prefixes = [];
*
* function callback(err, files, nextQuery, apiResponse) {
* prefixes = prefixes.concat(apiResponse.prefixes);
*
* if (nextQuery) {
* bucket.getFiles(nextQuery, callback);
* } else {
* // prefixes = The finished array of prefixes.
* }
* }
*
* bucket.getFiles({
* autoPaginate: false,
* delimiter: '/'
* }, callback);
* ```
*/
/**
* Create a Bucket object to interact with a Cloud Storage bucket.
*
* @class
* @hideconstructor
*
* @param {Storage} storage A {@link Storage} instance.
* @param {string} name The name of the bucket.
* @param {object} [options] Configuration object.
* @param {string} [options.userProject] User project.
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
* ```
*/
class Bucket extends ServiceObject<Bucket, BucketMetadata> {
name: string;
/**
* A reference to the {@link Storage} associated with this {@link Bucket}
* instance.
* @name Bucket#storage
* @type {Storage}
*/
storage: Storage;
/**
* A user project to apply to each request from this bucket.
* @name Bucket#userProject
* @type {string}
*/
userProject?: string;
acl: Acl;
iam: Iam;
crc32cGenerator: CRC32CValidatorGenerator;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getFilesStream(query?: GetFilesOptions): Readable {
// placeholder body, overwritten in constructor
return new Readable();
}
signer?: URLSigner;
private instanceRetryValue?: boolean;
instancePreconditionOpts?: PreconditionOptions;
constructor(storage: Storage, name: string, options?: BucketOptions) {
options = options || {};
// Allow for "gs://"-style input, and strip any trailing slashes.
name = name.replace(/^gs:\/\//, '').replace(/\/+$/, '');
const requestQueryObject: {
userProject?: string;
ifGenerationMatch?: number | string;
ifGenerationNotMatch?: number | string;
ifMetagenerationMatch?: number | string;
ifMetagenerationNotMatch?: number | string;
} = {};
if (options?.preconditionOpts?.ifGenerationMatch) {
requestQueryObject.ifGenerationMatch =
options.preconditionOpts.ifGenerationMatch;
}
if (options?.preconditionOpts?.ifGenerationNotMatch) {
requestQueryObject.ifGenerationNotMatch =
options.preconditionOpts.ifGenerationNotMatch;
}
if (options?.preconditionOpts?.ifMetagenerationMatch) {
requestQueryObject.ifMetagenerationMatch =
options.preconditionOpts.ifMetagenerationMatch;
}
if (options?.preconditionOpts?.ifMetagenerationNotMatch) {
requestQueryObject.ifMetagenerationNotMatch =
options.preconditionOpts.ifMetagenerationNotMatch;
}
const userProject = options.userProject;
if (typeof userProject === 'string') {
requestQueryObject.userProject = userProject;
}
const methods = {
/**
* Create a bucket.
*
* @method Bucket#create
* @param {CreateBucketRequest} [metadata] Metadata to set for the bucket.
* @param {CreateBucketCallback} [callback] Callback function.
* @returns {Promise<CreateBucketResponse>}
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
* bucket.create(function(err, bucket, apiResponse) {
* if (!err) {
* // The bucket was created successfully.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.create().then(function(data) {
* const bucket = data[0];
* const apiResponse = data[1];
* });
* ```
*/
create: {
reqOpts: {
qs: requestQueryObject,
},
},
/**
* IamDeleteBucketOptions Configuration options.
* @property {boolean} [ignoreNotFound = false] Ignore an error if
* the bucket does not exist.
* @property {string} [userProject] The ID of the project which will be
* billed for the request.
*/
/**
* @typedef {array} DeleteBucketResponse
* @property {object} 0 The full API response.
*/
/**
* @callback DeleteBucketCallback
* @param {?Error} err Request error, if any.
* @param {object} apiResponse The full API response.
*/
/**
* Delete the bucket.
*
* See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/delete| Buckets: delete API Documentation}
*
* @method Bucket#delete
* @param {DeleteBucketOptions} [options] Configuration options.
* @param {boolean} [options.ignoreNotFound = false] Ignore an error if
* the bucket does not exist.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {DeleteBucketCallback} [callback] Callback function.
* @returns {Promise<DeleteBucketResponse>}
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
* bucket.delete(function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.delete().then(function(data) {
* const apiResponse = data[0];
* });
*
* ```
* @example <caption>include:samples/buckets.js</caption>
* region_tag:storage_delete_bucket
* Another example:
*/
delete: {
reqOpts: {
qs: requestQueryObject,
},
},
/**
* @typedef {object} BucketExistsOptions Configuration options for Bucket#exists().
* @property {string} [userProject] The ID of the project which will be
* billed for the request.
*/
/**
* @typedef {array} BucketExistsResponse
* @property {boolean} 0 Whether the {@link Bucket} exists.
*/
/**
* @callback BucketExistsCallback
* @param {?Error} err Request error, if any.
* @param {boolean} exists Whether the {@link Bucket} exists.
*/
/**
* Check if the bucket exists.
*
* @method Bucket#exists
* @param {BucketExistsOptions} [options] Configuration options.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {BucketExistsCallback} [callback] Callback function.
* @returns {Promise<BucketExistsResponse>}
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
*
* bucket.exists(function(err, exists) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.exists().then(function(data) {
* const exists = data[0];
* });
* ```
*/
exists: {
reqOpts: {
qs: requestQueryObject,
},
},
/**
* @typedef {object} [GetBucketOptions] Configuration options for Bucket#get()
* @property {boolean} [autoCreate] Automatically create the object if