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);
Name | Type | Description |
---|---|---|
|
| No description. |
props
Optional
- Type: BucketProps
Methods
Preflight Methods
Name | Description |
---|---|
| Add cors configuration to the bucket. |
| Add a file to the bucket from system folder. |
| Add a file to the bucket that is uploaded when the app is deployed. |
| Run an inflight whenever a file is uploaded to the bucket. |
| Run an inflight whenever a file is deleted from the bucket. |
| Run an inflight whenever a file is uploaded, modified, or deleted from the bucket. |
| Run an inflight whenever a file is updated in the bucket. |
Inflight Methods
Name | Description |
---|---|
| Copy an object to a new location in the bucket. |
| Delete an existing object using a key from the bucket. |
| Check if an object exists in the bucket. |
| Retrieve an object from the bucket. |
| Retrieve a Json object from the bucket. |
| Retrieve existing objects keys from the bucket. |
| Get the metadata of an object in the bucket. |
| Returns a url to the given file. |
| Put an object in the bucket. |
| Put a Json object in the bucket. |
| Move an object to a new location in the bucket. |
| Returns a signed url to the given file. |
| Delete an object from the bucket if it exists. |
| Get an object from the bucket if it exists If the bytes returned are not a valid UTF-8 string, an error is thrown. |
| Gets an object from the bucket if it exists, parsing it as Json. |
addCorsRule
addCorsRule(value: BucketCorsOptions): void
Add cors configuration to the bucket.
value
Required
- Type: BucketCorsOptions
The cors configuration.
addFile
addFile(key: str, path: str, encoding?: str): void
Add a file to the bucket from system folder.
key
Required
- Type: str
The key or name to associate with the file.
path
Required
- Type: str
The path to the file on the local system.
encoding
Optional
- 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.
key
Required
- Type: str
body
Required
- Type: str
onCreate
onCreate(fn: IBucketEventHandler, opts?: BucketOnCreateOptions): void
Run an inflight whenever a file is uploaded to the bucket.
fn
Required
- Type: IBucketEventHandler
opts
Optional
- Type: BucketOnCreateOptions
onDelete
onDelete(fn: IBucketEventHandler, opts?: BucketOnDeleteOptions): void
Run an inflight whenever a file is deleted from the bucket.
fn
Required
- Type: IBucketEventHandler
opts
Optional
- Type: BucketOnDeleteOptions
onEvent
onEvent(fn: IBucketEventHandler, opts?: BucketOnEventOptions): void
Run an inflight whenever a file is uploaded, modified, or deleted from the bucket.
fn
Required
- Type: IBucketEventHandler
opts
Optional
- Type: BucketOnEventOptions
onUpdate
onUpdate(fn: IBucketEventHandler, opts?: BucketOnUpdateOptions): void
Run an inflight whenever a file is updated in the bucket.
fn
Required
- Type: IBucketEventHandler
opts
Optional
- Type: BucketOnUpdateOptions
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.
srcKey
Required
- Type: str
The key of the source object you wish to copy.
dstKey
Required
- 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.
key
Required
- Type: str
Key of the object.
opts
Optional
- Type: BucketDeleteOptions
Options available for delete an item from a bucket.
exists
inflight exists(key: str): bool
Check if an object exists in the bucket.
key
Required
- 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.
key
Required
- Type: str
Key of the object.
options
Optional
- Type: BucketGetOptions
Additional get options.
getJson
inflight getJson(key: str): Json
Retrieve a Json object from the bucket.
key
Required
- Type: str
Key of the object.
list
inflight list(prefix?: str): MutArray<str>
Retrieve existing objects keys from the bucket.
prefix
Optional
- 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.
key
Required
- Type: str
Key of the object.
publicUrl
inflight publicUrl(key: str): str
Returns a url to the given file.
key
Required
- Type: str
put
inflight put(key: str, body: str, options?: BucketPutOptions): void
Put an object in the bucket.
key
Required
- Type: str
Key of the object.
body
Required
- Type: str
Content of the object we want to store into the bucket.
options
Optional
- Type: BucketPutOptions
Additional options.
putJson
inflight putJson(key: str, body: Json): void
Put a Json object in the bucket.
key
Required
- Type: str
Key of the object.
body
Required
- Type: Json
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.
srcKey
Required
- Type: str
The key of the source object you wish to rename.
dstKey
Required
- 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.
key
Required
- Type: str
The key to access the cloud object.
options
Optional
- Type: BucketSignedUrlOptions
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.
key
Required
- 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.
key
Required
- Type: str
Key of the object.
options
Optional
- Type: BucketTryGetOptions
Additional get options.
tryGetJson
inflight tryGetJson(key: str): Json?
Gets an object from the bucket if it exists, parsing it as Json.
key
Required
- Type: str
Key of the object.
Static Functions
Name | Description |
---|---|
| A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. |
| 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.
host
Required
- Type: IInflightHost
ops
Required
- 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.
obj
Required
- Type: IResource
Properties
Name | Type | Description |
---|---|---|
| constructs.Node | The tree node. |
node
Required
node: Node;
- Type: constructs.Node
The tree node.
Structs
BucketCorsOptions
Cors Options for Bucket
.
Initializer
bring cloud;
let BucketCorsOptions = cloud.BucketCorsOptions{ ... };
Properties
Name | Type | Description |
---|---|---|
|
| The list of allowed methods. |
| MutArray<str> | The allowed origin. |
| MutArray<str> | The list of allowed headers. |
| MutArray<str> | The list of exposed headers. |
|
| How long the browser should cache preflight request results. |
allowedMethods
Required
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]
allowedOrigins
Required
allowedOrigins: MutArray<str>;
- Type: MutArray<str>
- Default: ["*"]
The allowed origin.
Example
"https://example.com"
allowedHeaders
Optional
allowedHeaders: MutArray<str>;
- Type: MutArray<str>
- Default: ["Content-Type", "Authorization"]
The list of allowed headers.
Example
["Content-Type"]
exposeHeaders
Optional
exposeHeaders: MutArray<str>;
- Type: MutArray<str>
- Default: []
The list of exposed headers.
Example
["Content-Type"]
maxAge
Optional
maxAge: duration;
- Type: duration
- Default: 300 seconds
How long the browser should cache preflight request results.
BucketDeleteOptions
Options for Bucket.delete()
.
Initializer
bring cloud;
let BucketDeleteOptions = cloud.BucketDeleteOptions{ ... };
Properties
Name | Type | Description |
---|---|---|
| bool | Check failures on the method and retrieve errors if any. |
mustExist
Optional
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
Name | Type | Description |
---|---|---|
| str | The bucket key that triggered the event. |
|
| Type of event. |
key
Required
key: str;
- Type: str
The bucket key that triggered the event.
type
Required
type: BucketEventType;
- Type: BucketEventType
Type of event.
BucketGetOptions
Options for Bucket.get()
.
Initializer
bring cloud;
let BucketGetOptions = cloud.BucketGetOptions{ ... };
Properties
Name | Type | Description |
---|---|---|
| num | The ending byte to read up to (including). |
| num | The starting byte to read from. |
endByte
Optional
endByte: num;
- Type: num
- Default: undefined
The ending byte to read up to (including).
startByte
Optional
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
Name | Type | Description |
---|---|---|
| bool | Whether to add default cors configuration. |
|
| Custom cors configuration for the bucket. |
| bool | Whether the bucket's objects should be publicly accessible. |
cors
Optional
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
}
corsOptions
Optional
corsOptions: BucketCorsOptions;
- Type: BucketCorsOptions
- Default: All origins, methods, headers are allowed.
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
}
public
Optional
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
Name | Type | Description |
---|---|---|
| str | The HTTP Content-Type of the object. |
contentType
Required
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
Name | Type | Description |
---|---|---|
|
| The action allowed by the signed URL. |
|
| The duration for the signed URL to expire. |
action
Optional
action: BucketSignedUrlAction;
- Type: BucketSignedUrlAction
- Default: BucketSignedUrlAction.DOWNLOAD
The action allowed by the signed URL.
duration
Optional
duration: duration;
- Type: duration
- Default: 15m
The duration for the signed URL to expire.
BucketTryGetOptions
Options for Bucket.tryGet()
.
Initializer
bring cloud;
let BucketTryGetOptions = cloud.BucketTryGetOptions{ ... };
Properties
Name | Type | Description |
---|---|---|
| num | The ending byte to read up to (including). |
| num | The starting byte to read from. |
endByte
Optional
endByte: num;
- Type: num
- Default: undefined
The ending byte to read up to (including).
startByte
Optional
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
Name | Type | Description |
---|---|---|
|
| The time the object was last modified. |
| num | The size of the object in bytes. |
| str | The content type of the object, if it is known. |
lastModified
Required
lastModified: datetime;
- Type: datetime
The time the object was last modified.
size
Required
size: num;
- Type: num
The size of the object in bytes.
contentType
Optional
contentType: str;
- Type: str
The content type of the object, if it is known.
Protocols
IBucketEventHandler
-
Extends: IInflight
-
Implemented By: IBucketEventHandler
Inflight client: @winglang/sdk.cloud.IBucketEventHandlerClient
A resource with an inflight "handle" method that can be passed to the bucket events.
IBucketEventHandlerClient
- Implemented By: IBucketEventHandlerClient
A resource with an inflight "handle" method that can be passed to the bucket events.
Methods
Name | Description |
---|---|
| 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.
key
Required
- Type: str
type
Required
- Type: BucketEventType
Enums
BucketEventType
Bucket events to subscribe to.
Members
Name | Description |
---|---|
| Create. |
| Delete. |
| Update. |
CREATE
Create.
DELETE
Delete.
UPDATE
Update.
BucketSignedUrlAction
Specifies the action permitted by a presigned URL for a bucket.
Members
Name | Description |
---|---|
| Represents a HTTP GET request for a presigned URL, allowing read access for an object in the bucket. |
| 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.