Skip to main content

Bucket

The cloud.Bucket resource represents a container for storing data in the cloud.

Buckets are a common way to store arbitrary files (images, videos, etc.), but can also be used to store structured data like JSON or CSV files.

Buckets in the cloud use object storage, which is optimized for storing large amounts of data with high availability. Unlike other kinds of storage like file storage, data is not stored in a hierarchical structure, but rather as a flat list of objects, each associated with a key.

Usage​

Defining a bucket​

bring cloud;

let bucket = new cloud.Bucket(
public: true, // optional, defaults to `false`
);

Populating objects during deployment​

If you have static data that you want to upload to the bucket each time your app is deployed, you can call the preflight method addObject:

bring cloud;

let bucket = new cloud.Bucket();

bucket.addObject("my-file.txt", "Hello, world!");

Using a bucket inflight​

bring cloud;

let bucket = new cloud.Bucket();

let bucketFunc = inflight () => {
bucket.put("file.txt", "Hello, world!");
bucket.putJson("person.json", Json { name: "Alice" });

let fileData = bucket.get("file.txt");
assert(fileData == "Hello, world!");

let jsonData = bucket.getJson("person.json");
assert(jsonData.get("name") == "Alice");

let keys = bucket.list();
assert(keys.at(0) == "file.txt");
assert(keys.at(1) == "person.json");

bucket.delete("file.txt");
};

new cloud.Function(bucketFunc);

Run code on bucket events​

You can use the preflight methods onCreate, onUpdate, and onDelete to define code that should run when an object is uploaded, updated, or removed from the bucket. Use the onEvent method for responding to any event.

Each method creates a new cloud.Function resource which will be triggered by the given event type.

bring cloud;

let store = new cloud.Bucket();
let copies = new cloud.Bucket() as "Backup";

store.onCreate(inflight (key: str) => {
let data = store.get(key);
if !key.endsWith(".log") {
copies.put(key, data);
}
});

store.onDelete(inflight (key: str) => {
copies.delete(key);
log("Deleted {key}");
});

Configuring CORS​

By default, buckets are configured with CORS for any origin. When a bucket is private (the default), CORS options only come into play when the bucket's objects are accessed through a signed URL.

bring cloud;
bring http;

let uploads = new cloud.Bucket(
// these are the default values
public: false,
cors: true,
corsOptions: {
allowedMethods: [http.HttpMethod.GET, http.HttpMethod.POST, http.HttpMethod.PUT, http.HttpMethod.DELETE, http.HttpMethod.HEAD],
allowedOrigins: ["*"],
allowedHeaders: ["*"],
exposeHeaders: [],
maxAge: 0s
},
);

The CORS configuration can be disabled by passing cors: false to the constructor. CORS rules can also be configured after the bucket is created by calling the addCorsRule method:

bring cloud;
bring http;

let bucket = new cloud.Bucket(
cors: false, // disable any default CORS rules
);

bucket.addCorsRule({
allowedOrigins: ["https://example.com"],
allowedMethods: [http.HttpMethod.GET],
});

Target-specific details​

Simulator (sim)​

Under the hood, the simulator uses a temporary local directory to store bucket data.

Note that bucket data is not persisted between simulator runs.

AWS (tf-aws and awscdk)​

The AWS implementation of cloud.Bucket uses Amazon S3.

Azure (tf-azure)​

The Azure implementation of cloud.Bucket uses Azure Blob Storage.

GCP (tf-gcp)​

The Google Cloud implementation of cloud.Bucket uses Google Cloud Storage.

API Reference ​

Bucket ​

A cloud object store.

Initializers ​

bring cloud;

new cloud.Bucket(props?: BucketProps);
NameTypeDescription
props
BucketProps
No description.

propsOptional ​

Methods ​

Preflight Methods​
NameDescription
addCorsRule
Add cors configuration to the bucket.
addFile
Add a file to the bucket from system folder.
addObject
Add a file to the bucket that is uploaded when the app is deployed.
onCreate
Run an inflight whenever a file is uploaded to the bucket.
onDelete
Run an inflight whenever a file is deleted from the bucket.
onEvent
Run an inflight whenever a file is uploaded, modified, or deleted from the bucket.
onUpdate
Run an inflight whenever a file is updated in the bucket.
Inflight Methods​
NameDescription
copy
Copy an object to a new location in the bucket.
delete
Delete an existing object using a key from the bucket.
exists
Check if an object exists in the bucket.
get
Retrieve an object from the bucket.
getJson
Retrieve a Json object from the bucket.
list
Retrieve existing objects keys from the bucket.
metadata
Get the metadata of an object in the bucket.
publicUrl
Returns a url to the given file.
put
Put an object in the bucket.
putJson
Put a Json object in the bucket.
rename
Move an object to a new location in the bucket.
signedUrl
Returns a signed url to the given file.
tryDelete
Delete an object from the bucket if it exists.
tryGet
Get an object from the bucket if it exists If the bytes returned are not a valid UTF-8 string, an error is thrown.
tryGetJson
Gets an object from the bucket if it exists, parsing it as Json.

addCorsRule ​
addCorsRule(value: BucketCorsOptions): void

Add cors configuration to the bucket.

valueRequired ​

The cors configuration.


addFile ​
addFile(key: str, path: str, encoding?: str): void

Add a file to the bucket from system folder.

keyRequired ​
  • Type: str

The key or name to associate with the file.


pathRequired ​
  • Type: str

The path to the file on the local system.


encodingOptional ​
  • Type: str

The encoding to use when reading the file.

Defaults to "utf-8".


addObject ​
addObject(key: str, body: str): void

Add a file to the bucket that is uploaded when the app is deployed.

TODO: In the future this will support uploading any Blob type or referencing a file from the local filesystem.

keyRequired ​
  • Type: str

bodyRequired ​
  • Type: str

onCreate ​
onCreate(fn: IBucketEventHandler, opts?: BucketOnCreateOptions): void

Run an inflight whenever a file is uploaded to the bucket.

fnRequired ​

optsOptional ​

onDelete ​
onDelete(fn: IBucketEventHandler, opts?: BucketOnDeleteOptions): void

Run an inflight whenever a file is deleted from the bucket.

fnRequired ​

optsOptional ​

onEvent ​
onEvent(fn: IBucketEventHandler, opts?: BucketOnEventOptions): void

Run an inflight whenever a file is uploaded, modified, or deleted from the bucket.

fnRequired ​

optsOptional ​

onUpdate ​
onUpdate(fn: IBucketEventHandler, opts?: BucketOnUpdateOptions): void

Run an inflight whenever a file is updated in the bucket.

fnRequired ​

optsOptional ​

copy ​
inflight copy(srcKey: str, dstKey: str): void

Copy an object to a new location in the bucket.

If the destination object already exists, it will be overwritten.

srcKeyRequired ​
  • Type: str

The key of the source object you wish to copy.


dstKeyRequired ​
  • Type: str

The key of the destination object after copying.


delete ​
inflight delete(key: str, opts?: BucketDeleteOptions): void

Delete an existing object using a key from the bucket.

keyRequired ​
  • Type: str

Key of the object.


optsOptional ​

Options available for delete an item from a bucket.


exists ​
inflight exists(key: str): bool

Check if an object exists in the bucket.

keyRequired ​
  • Type: str

Key of the object.


get ​
inflight get(key: str, options?: BucketGetOptions): str

Retrieve an object from the bucket.

If the bytes returned are not a valid UTF-8 string, an error is thrown.

keyRequired ​
  • Type: str

Key of the object.


optionsOptional ​

Additional get options.


getJson ​
inflight getJson(key: str): Json

Retrieve a Json object from the bucket.

keyRequired ​
  • Type: str

Key of the object.


list ​
inflight list(prefix?: str): MutArray<str>

Retrieve existing objects keys from the bucket.

prefixOptional ​
  • Type: str

Limits the response to keys that begin with the specified prefix.


metadata ​
inflight metadata(key: str): ObjectMetadata

Get the metadata of an object in the bucket.

keyRequired ​
  • Type: str

Key of the object.


publicUrl ​
inflight publicUrl(key: str): str

Returns a url to the given file.

keyRequired ​
  • Type: str

put ​
inflight put(key: str, body: str, options?: BucketPutOptions): void

Put an object in the bucket.

keyRequired ​
  • Type: str

Key of the object.


bodyRequired ​
  • Type: str

Content of the object we want to store into the bucket.


optionsOptional ​

Additional options.


putJson ​
inflight putJson(key: str, body: Json): void

Put a Json object in the bucket.

keyRequired ​
  • Type: str

Key of the object.


bodyRequired ​

Json object that we want to store into the bucket.


rename ​
inflight rename(srcKey: str, dstKey: str): void

Move an object to a new location in the bucket.

If the destination object already exists, it will be overwritten. Returns once the renaming is finished.

srcKeyRequired ​
  • Type: str

The key of the source object you wish to rename.


dstKeyRequired ​
  • Type: str

The key of the destination object after renaming.


signedUrl ​
inflight signedUrl(key: str, options?: BucketSignedUrlOptions): str

Returns a signed url to the given file.

keyRequired ​
  • Type: str

The key to access the cloud object.


optionsOptional ​

The signedUrlOptions where you can provide the configurations of the signed url.


tryDelete ​
inflight tryDelete(key: str): bool

Delete an object from the bucket if it exists.

keyRequired ​
  • Type: str

Key of the object.


tryGet ​
inflight tryGet(key: str, options?: BucketTryGetOptions): str?

Get an object from the bucket if it exists If the bytes returned are not a valid UTF-8 string, an error is thrown.

keyRequired ​
  • Type: str

Key of the object.


optionsOptional ​

Additional get options.


tryGetJson ​
inflight tryGetJson(key: str): Json?

Gets an object from the bucket if it exists, parsing it as Json.

keyRequired ​
  • Type: str

Key of the object.


Static Functions ​

NameDescription
onLiftType
A hook called by the Wing compiler once for each inflight host that needs to use this type inflight.
toInflight
Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource.

onLiftType ​
bring cloud;

cloud.Bucket.onLiftType(host: IInflightHost, ops: MutArray<str>);

A hook called by the Wing compiler once for each inflight host that needs to use this type inflight.

The list of requested inflight methods needed by the inflight host are given by ops.

This method is commonly used for adding permissions, environment variables, or other capabilities to the inflight host.

hostRequired ​

opsRequired ​
  • Type: MutArray<str>

toInflight ​
bring cloud;

cloud.Bucket.toInflight(obj: IResource);

Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource.

NOTE: This statement must be executed within an async context.

objRequired ​

Properties ​

NameTypeDescription
node
constructs.NodeThe tree node.

nodeRequired ​
node: Node;
  • Type: constructs.Node

The tree node.


Structs ​

BucketCorsOptions ​

Cors Options for Bucket.

Initializer ​

bring cloud;

let BucketCorsOptions = cloud.BucketCorsOptions{ ... };

Properties ​

NameTypeDescription
allowedMethods
MutArray<HttpMethod>
The list of allowed methods.
allowedOrigins
MutArray<str>The allowed origin.
allowedHeaders
MutArray<str>The list of allowed headers.
exposeHeaders
MutArray<str>The list of exposed headers.
maxAge
duration
How long the browser should cache preflight request results.

allowedMethodsRequired ​
allowedMethods: MutArray<HttpMethod>;
  • Type: MutArray<HttpMethod>
  • Default: [HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH, HttpMethod.DELETE, HttpMethod.HEAD, HttpMethod.OPTIONS]

The list of allowed methods.


Example

[HttpMethod.GET, HttpMethod.POST]
allowedOriginsRequired ​
allowedOrigins: MutArray<str>;
  • Type: MutArray<str>
  • Default: ["*"]

The allowed origin.


Example

"https://example.com"
allowedHeadersOptional ​
allowedHeaders: MutArray<str>;
  • Type: MutArray<str>
  • Default: ["Content-Type", "Authorization"]

The list of allowed headers.


Example

["Content-Type"]
exposeHeadersOptional ​
exposeHeaders: MutArray<str>;
  • Type: MutArray<str>
  • Default: []

The list of exposed headers.


Example

["Content-Type"]
maxAgeOptional ​
maxAge: duration;

How long the browser should cache preflight request results.


BucketDeleteOptions ​

Options for Bucket.delete().

Initializer ​

bring cloud;

let BucketDeleteOptions = cloud.BucketDeleteOptions{ ... };

Properties ​

NameTypeDescription
mustExist
boolCheck failures on the method and retrieve errors if any.

mustExistOptional ​
mustExist: bool;
  • Type: bool
  • Default: false

Check failures on the method and retrieve errors if any.


BucketEvent ​

On_event notification payload- will be in use after solving issue: https://github.com/winglang/wing/issues/1927.

Initializer ​

bring cloud;

let BucketEvent = cloud.BucketEvent{ ... };

Properties ​

NameTypeDescription
key
strThe bucket key that triggered the event.
type
BucketEventType
Type of event.

keyRequired ​
key: str;
  • Type: str

The bucket key that triggered the event.


typeRequired ​
type: BucketEventType;

Type of event.


BucketGetOptions ​

Options for Bucket.get().

Initializer ​

bring cloud;

let BucketGetOptions = cloud.BucketGetOptions{ ... };

Properties ​

NameTypeDescription
endByte
numThe ending byte to read up to (including).
startByte
numThe starting byte to read from.

endByteOptional ​
endByte: num;
  • Type: num
  • Default: undefined

The ending byte to read up to (including).


startByteOptional ​
startByte: num;
  • Type: num
  • Default: undefined

The starting byte to read from.


BucketOnCreateOptions ​

onCreate event options.

Initializer ​

bring cloud;

let BucketOnCreateOptions = cloud.BucketOnCreateOptions{ ... };

BucketOnDeleteOptions ​

onDelete event options.

Initializer ​

bring cloud;

let BucketOnDeleteOptions = cloud.BucketOnDeleteOptions{ ... };

BucketOnEventOptions ​

onEvent options.

Initializer ​

bring cloud;

let BucketOnEventOptions = cloud.BucketOnEventOptions{ ... };

BucketOnUpdateOptions ​

onUpdate event options.

Initializer ​

bring cloud;

let BucketOnUpdateOptions = cloud.BucketOnUpdateOptions{ ... };

BucketProps ​

Options for Bucket.

Initializer ​

bring cloud;

let BucketProps = cloud.BucketProps{ ... };

Properties ​

NameTypeDescription
cors
boolWhether to add default cors configuration.
corsOptions
BucketCorsOptions
Custom cors configuration for the bucket.
forceDestroy
boolWhether to allow the bucket to be deleted even if it is not empty.
public
boolWhether the bucket's objects should be publicly accessible.

corsOptional ​
cors: bool;
  • Type: bool
  • Default: true

Whether to add default cors configuration.

The default cors configuration is equivalent to calling addCorsRule with the following options: { allowHeaders: [""], allowOrigins: [""], allowMethods: ["DELETE", "GET", "HEAD", "POST", "PUT"], exposeHeaders: [], maxAge: 0s }


corsOptionsOptional ​
corsOptions: BucketCorsOptions;

Custom cors configuration for the bucket.

The default cors configuration is equivalent to calling addCorsRule with the following options: { allowHeaders: [""], allowOrigins: [""], allowMethods: ["DELETE", "GET", "HEAD", "POST", "PUT"], exposeHeaders: [], maxAge: 0s }


forceDestroyOptional ​
forceDestroy: bool;
  • Type: bool
  • Default: false

Whether to allow the bucket to be deleted even if it is not empty.


publicOptional ​
public: bool;
  • Type: bool
  • Default: false

Whether the bucket's objects should be publicly accessible.


BucketPutOptions ​

Options for Bucket.put().

Initializer ​

bring cloud;

let BucketPutOptions = cloud.BucketPutOptions{ ... };

Properties ​

NameTypeDescription
contentType
strThe HTTP Content-Type of the object.

contentTypeRequired ​
contentType: str;
  • Type: str
  • Default: Determined by file extension or fallback to "application/octet-stream"

The HTTP Content-Type of the object.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type


BucketSignedUrlOptions ​

Options for Bucket.signedUrl().

Initializer ​

bring cloud;

let BucketSignedUrlOptions = cloud.BucketSignedUrlOptions{ ... };

Properties ​

NameTypeDescription
action
BucketSignedUrlAction
The action allowed by the signed URL.
duration
duration
The duration for the signed URL to expire.

actionOptional ​
action: BucketSignedUrlAction;

The action allowed by the signed URL.


durationOptional ​
duration: duration;

The duration for the signed URL to expire.


BucketTryGetOptions ​

Options for Bucket.tryGet().

Initializer ​

bring cloud;

let BucketTryGetOptions = cloud.BucketTryGetOptions{ ... };

Properties ​

NameTypeDescription
endByte
numThe ending byte to read up to (including).
startByte
numThe starting byte to read from.

endByteOptional ​
endByte: num;
  • Type: num
  • Default: undefined

The ending byte to read up to (including).


startByteOptional ​
startByte: num;
  • Type: num
  • Default: undefined

The starting byte to read from.


ObjectMetadata ​

Metadata of a bucket object.

Initializer ​

bring cloud;

let ObjectMetadata = cloud.ObjectMetadata{ ... };

Properties ​

NameTypeDescription
lastModified
datetime
The time the object was last modified.
size
numThe size of the object in bytes.
contentType
strThe content type of the object, if it is known.

lastModifiedRequired ​
lastModified: datetime;

The time the object was last modified.


sizeRequired ​
size: num;
  • Type: num

The size of the object in bytes.


contentTypeOptional ​
contentType: str;
  • Type: str

The content type of the object, if it is known.


Protocols ​

IBucketEventHandler ​

Inflight client: @winglang/sdk.cloud.IBucketEventHandlerClient

A resource with an inflight "handle" method that can be passed to the bucket events.

IBucketEventHandlerClient ​

A resource with an inflight "handle" method that can be passed to the bucket events.

Methods ​

NameDescription
handle
Function that will be called when an event notification is fired.

handle ​
inflight handle(key: str, type: BucketEventType): void

Function that will be called when an event notification is fired.

keyRequired ​
  • Type: str

typeRequired ​

Enums ​

BucketEventType ​

Bucket events to subscribe to.

Members ​

NameDescription
CREATE
Create.
DELETE
Delete.
UPDATE
Update.

CREATE ​

Create.


DELETE ​

Delete.


UPDATE ​

Update.


BucketSignedUrlAction ​

Specifies the action permitted by a presigned URL for a bucket.

Members ​

NameDescription
DOWNLOAD
Represents a HTTP GET request for a presigned URL, allowing read access for an object in the bucket.
UPLOAD
Represents a HTTP PUT request for a presigned URL, allowing write access for an object in the bucket.

DOWNLOAD ​

Represents a HTTP GET request for a presigned URL, allowing read access for an object in the bucket.


UPLOAD ​

Represents a HTTP PUT request for a presigned URL, allowing write access for an object in the bucket.