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}");
});

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
propsBucketPropsNo description.

propsOptional

Methods

Preflight Methods
NameDescription
addFileAdd a file to the bucket from system folder.
addObjectAdd a file to the bucket that is uploaded when the app is deployed.
onCreateRun an inflight whenever a file is uploaded to the bucket.
onDeleteRun an inflight whenever a file is deleted from the bucket.
onEventRun an inflight whenever a file is uploaded, modified, or deleted from the bucket.
onUpdateRun an inflight whenever a file is updated in the bucket.
Inflight Methods
NameDescription
copyCopy an object to a new location in the bucket.
deleteDelete an existing object using a key from the bucket.
existsCheck if an object exists in the bucket.
getRetrieve an object from the bucket.
getJsonRetrieve a Json object from the bucket.
listRetrieve existing objects keys from the bucket.
metadataGet the metadata of an object in the bucket.
publicUrlReturns a url to the given file.
putPut an object in the bucket.
putJsonPut a Json object in the bucket.
renameMove an object to a new location in the bucket.
signedUrlReturns a signed url to the given file.
tryDeleteDelete an object from the bucket if it exists.
tryGetGet an object from the bucket if it exists If the bytes returned are not a valid UTF-8 string, an error is thrown.
tryGetJsonGets an object from the bucket if it exists, parsing it as Json.

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
onLiftTypeA hook called by the Wing compiler once for each inflight host that needs to use this type inflight.

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>

Properties

NameTypeDescription
nodeconstructs.NodeThe tree node.

nodeRequired
node: Node;
  • Type: constructs.Node

The tree node.


Structs

BucketDeleteOptions

Options for Bucket.delete().

Initializer

bring cloud;

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

Properties

NameTypeDescription
mustExistboolCheck 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
keystrThe bucket key that triggered the event.
typeBucketEventTypeType 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
endBytenumThe ending byte to read up to (including).
startBytenumThe 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
publicboolWhether the bucket's objects should be publicly accessible.

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
contentTypestrThe 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
actionBucketSignedUrlActionThe action allowed by the signed URL.
durationdurationThe 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
endBytenumThe ending byte to read up to (including).
startBytenumThe 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
lastModifieddatetimeThe time the object was last modified.
sizenumThe size of the object in bytes.
contentTypestrThe 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
handleFunction 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
CREATECreate.
DELETEDelete.
UPDATEUpdate.

CREATE

Create.


DELETE

Delete.


UPDATE

Update.


BucketSignedUrlAction

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

Members

NameDescription
DOWNLOADRepresents a HTTP GET request for a presigned URL, allowing read access for an object in the bucket.
UPLOADRepresents 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.