bucket
Declare a bucket of files in a luna, and store, read, list and sign URLs for them with ctx.blobs.
bucket declares a bucket of objects, files with a content type and metadata, under the luna type’s blobs option. A handler uses it as ctx.blobs.<name>.
import { bucket, defineLuna, t } from "luna";
export const Profile = defineLuna({
name: "Profile",
key: { id: t.string() },
blobs: {
files: bucket({ path: "files/{name...}" }),
},
handlers: (h) => ({
save: h({ args: { name: t.string(), text: t.string() } }, async (ctx, { name, text }) => {
await ctx.blobs.files.put(`files/${name}`, text);
}),
read: h({ args: { name: t.string() } }, (ctx, { name }) => ctx.blobs.files.text(`files/${name}`)),
}),
});
Reference
bucket(spec)
pathstring
Where objects go: segments split by `/`, where `{name}` stands for one segment and a last `{name...}` for the rest.
stringtypes?string[]
The content types allowed, such as `"image/png"` or `"image/*"`, and with none, any type.
string[]maxSize?number
The largest object in bytes, at most 10 GiB.
number10 GiBmeta?Ty<M>
Each object's metadata type, built with `t`.
Ty<M>public?boolean
Anyone may read objects at a plain URL, and otherwise only through a signed one.
booleanfalseonUpload?(ctx, object: BlobObject<M>) => void
Runs when an upload through a signed URL finishes, and throwing rejects the upload.
(ctx, object: BlobObject<M>) => voidBucket
namestring
The bucket's name.
stringput(path, data, opts?)Promise<BlobObject<M>>
Stores an object of up to 256 MiB at `path`, replacing what is there, with `opts.contentType` and `opts.meta`.
Promise<BlobObject<M>>get(path, opts?)Promise<{ object: BlobObject<M>; bytes: Uint8Array } | null>
The object and its bytes, or `null`, with `opts.range` as `[from, to)` in bytes.
Promise<{ object: BlobObject<M>; bytes: Uint8Array } | null>text(path)Promise<string | null>
The object's bytes as UTF-8 text, or `null`.
Promise<string | null>head(path)BlobObject<M> | null
The object without its bytes, or `null`.
BlobObject<M> | nulllist(opts?){ objects: BlobObject<M>[]; cursor: string | null }
Objects whose path starts with `prefix`, in path order, `limit` at a time, 100 by default and 1,000 at most.
{ objects: BlobObject<M>[]; cursor: string | null }delete(path)boolean
Deletes the object, and returns `false` if there was none.
booleancopy(path, to)BlobObject | null
Copies the object to a `BlobDestination`, or returns `null` if there was none.
BlobObject | nullmove(path, to)BlobObject | null
Moves the object to a `BlobDestination`, or returns `null` if there was none.
BlobObject | nullsignUpload(path, opts?)SignedUrl
A URL an app uploads `path` to with `PUT`, limited by `opts.maxSize` and `opts.contentType`.
SignedUrlsignDownload(path, opts?)SignedUrl
A URL an app downloads `path` from with `GET`.
SignedUrldata is a Uint8Array or a string. A string is stored as text/plain; charset=utf-8 and bytes as application/octet-stream, unless you pass contentType. opts.expiresIn of both sign methods is in milliseconds, one hour by default.
BlobObject
bucketstring
The bucket it is in.
stringpathstring
Its path.
stringhashstring
Its ETag, which changes whenever the bytes do.
stringsizenumber
Its size in bytes.
numbercontentTypestring
Its content type.
stringmetaM | null
Its metadata.
M | nullcreatednumber
When it was made, in milliseconds since the epoch.
numberupdatednumber
When it last changed, in milliseconds since the epoch.
numberSignedUrl
urlstring
A path and query, to add to your app's URL.
stringmethod"PUT" | "GET"
The method to send.
"PUT" | "GET"expiresnumber
When it stops working, in milliseconds since the epoch.
numberBlobDestination
A path in the same bucket as a string, or { bucket, path } for another bucket of the same luna.
Good to know
- An object written by a handler is there once the handler commits. A handler that fails leaves no object behind.
- An object’s path must match its bucket’s
path, its type must be one oftypes, and its size at mostmaxSize. Otherwise the write fails. putandgethandle at most 256 MiB at once. Read a larger object in parts withrange, and upload one throughsignUpload.onUploadruns in one transaction with the object it commits. It must be synchronous, since writes cannot span anawait. Start slower work withctx.send.- A signed URL is its own credential. Downloads through it, or from a public bucket, do not wake the luna.
- A public bucket’s object is read at the same path as its signed download URL, without the query.
- Rows that reference an object with
t.blobReffollow theironDeletewhen it is deleted. By default the delete fails. A move inside the bucket takes those references with it.
Examples
Read part of a large object
head: h({ args: { name: t.string() } }, async (ctx, { name }) => {
const got = await ctx.blobs.files.get(`files/${name}`, { range: [0, 1024] });
return got ? { type: got.object.contentType, first: got.bytes.length } : null;
}),
Let an app upload a photo
import { bucket, defineLuna, t, table } from "luna";
export const Profile = defineLuna({
name: "Profile",
key: { id: t.string() },
schema: { uploads: table({ id: t.id(), path: t.string(), size: t.int() }) },
blobs: {
photos: bucket({
path: "photos/{photo}",
types: ["image/*"],
maxSize: 20 * 1024 * 1024,
meta: t.object({ caption: t.string() }),
onUpload: (ctx, object) => {
ctx.db.uploads.insert({ path: object.path, size: object.size });
},
}),
},
handlers: (h) => ({
uploadUrl: h({ args: { photo: t.string() } }, (ctx, { photo }) =>
ctx.blobs.photos.signUpload(`photos/${photo}`, { expiresIn: 600_000, contentType: "image/png" }),
),
}),
});
The app sends the file’s bytes with PUT to LUNA_URL followed by url.
Serve avatars to anyone
blobs: {
avatars: bucket({ path: "avatar", types: ["image/png", "image/jpeg"], public: true }),
},
Delete empty objects a page at a time
tidy: h({}, (ctx) => {
let page = ctx.blobs.files.list({ prefix: "files/", limit: 100 });
for (;;) {
for (const o of page.objects) if (o.size === 0) ctx.blobs.files.delete(o.path);
if (!page.cursor) break;
page = ctx.blobs.files.list({ prefix: "files/", cursor: page.cursor, limit: 100 });
}
}),
Copy a photo to another bucket
useAsAvatar: h({ args: { photo: t.string() } }, (ctx, { photo }) => {
ctx.blobs.photos.copy(`photos/${photo}`, { bucket: "avatars", path: "avatar" });
}),
A copy moves no bytes.