Upload from an app
Sign upload and download URLs in a handler, check each upload with onUpload, and serve files from a public bucket.
An app’s photos and videos should not travel as handler arguments, where bytes are base64 text inside JSON. A handler signs a URL instead, and the app sends the bytes straight to it.
The luna does not run while the bytes arrive. It runs once at the end, to record the file.
Sign an upload URL
signUpload returns a URL for one path of a bucket. Pass a contentType and a maxSize to limit what the app may send there.
import { bucket, defineLuna, t, table } from "luna";
export const User = defineLuna({
name: "User",
visibility: "public",
key: { id: t.string() },
schema: {
profile: table({ avatar: t.string().optional() }, { singleRow: true }),
},
blobs: {
avatars: bucket({ path: "avatars/{file}", types: ["image/png", "image/jpeg"] }),
},
handlers: (h) => ({
avatarUpload: h({ args: { type: t.enum(["image/png", "image/jpeg"]) } }, (ctx, { type }) => {
const file = type === "image/png" ? "avatar.png" : "avatar.jpg";
return ctx.blobs.avatars.signUpload(`avatars/${file}`, { contentType: type, maxSize: 1024 * 1024 });
}),
}),
});
The handler returns a SignedUrl with three fields.
| Field | Holds |
|---|---|
url |
A path and query to add to your app’s LUNA_URL |
method |
PUT for an upload, GET for a download |
expires |
When the URL stops working, in milliseconds since the Unix epoch |
A URL lasts an hour unless you pass expiresIn in milliseconds. It lasts at most 7 days.
A public luna type lets any app user ask for a URL. Check who is asking first, as Check who is calling shows.
Send the file from the app
The app asks the handler for a URL, then sends the file with fetch. The URL is its own credential, so the request carries no key.
import { createClient } from "luna/client";
import type { User } from "../luna/lunas/user.ts";
const LUNA_URL = process.env.LUNA_URL!;
const client = createClient({ url: LUNA_URL, key: process.env.LUNA_KEY });
export async function uploadAvatar(userId: string, file: Blob & { type: "image/png" | "image/jpeg" }) {
const signed = await client.luna<typeof User>("User", userId).mutate("avatarUpload", { type: file.type });
const response = await fetch(LUNA_URL + signed.url, {
method: signed.method,
headers: { "content-type": file.type },
body: file,
});
if (!response.ok) throw new Error(`upload failed: ${response.status}`);
return response.json();
}
When the upload succeeds, the response has status 200 and the stored file’s BlobObject as JSON. A request without a Content-Type header is stored as application/octet-stream.
Check the size and type
Luna checks every upload against the URL and the bucket before the file is kept.
| Check | Status when it fails |
|---|---|
| The signature is right and the URL has not expired | 403 |
The size is within the URL’s maxSize and the bucket’s |
413 |
The Content-Type header is exactly the URL’s contentType |
400 |
The content type is one of the bucket’s types |
400 |
A URL’s maxSize can only lower the bucket’s own limit. One URL takes uploads to its one path, and a new upload replaces the file there.
Check each upload in onUpload
Give the bucket an onUpload hook to act on each upload as it finishes. It runs in one transaction with the new file, so its writes and the file are kept together.
avatars: bucket({
path: "avatars/{file}",
types: ["image/png", "image/jpeg"],
onUpload: (ctx, object) => {
if (object.size === 0) throw new Error("the file is empty");
ctx.db.profile.set({ avatar: object.path });
},
}),
Throwing, or calling ctx.fail, rejects the upload. The file is not kept, and the app’s request fails with the error.
onUpload must be synchronous, because its writes cannot span an await. Start slower work, such as making a thumbnail, with ctx.send.
Sign a download URL
Files in a bucket are private unless it is public. signDownload returns a URL the app can read the file from with GET.
avatarUrl: h({}, (ctx) => {
const avatar = ctx.db.profile.get()?.avatar;
return avatar ? ctx.blobs.avatars.signDownload(avatar, { expiresIn: 3_600_000 }) : null;
}),
Put LUNA_URL + url in an <img> tag, or read it with fetch. A download does not wake the luna.
Downloads answer Range requests with status 206, and send an ETag. A request with a matching If-None-Match gets status 304 without the bytes.
Serve files from a public bucket
A bucket with public: true serves its files to anyone at a plain URL, with no signature.
banners: bucket({ path: "banners/{file}", public: true }),
A file of a public bucket is at this URL:
<LUNA_URL>/<TYPE>/<KEY>/blobs/<BUCKET>/<PATH>
For the User with key u1, that is <LUNA_URL>/User/u1/blobs/banners/banners/top.png. The path is the file’s whole path, so its first segment repeats here.
Uploads to a public bucket still need a signed URL. Browsers and other caches may keep a public file for up to 60 seconds after it changes.
Next steps
- Store files covers reading, listing and deleting files from a handler.
- Check who is calling decides which app users may ask for a URL.
- bucket lists every option and method.