Skip to content

Commit

Permalink
feat(cloudflare-r2-binding): allow specify raw type (#519)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Dec 10, 2024
1 parent 0c4d9fd commit 90ae631
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
9 changes: 9 additions & 0 deletions docs/2.drivers/cloudflare.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,12 @@ const storage = createStorage({

- `binding`: Bucket binding or name. Default is `BUCKET`.
- `base`: Prefix all keys with base.

**Transaction options:**

- `getItemRaw(key, { type: "..." })`
- `type: "object"`: Return the [R2 object body](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/#r2objectbody-definition).
- `type: "stream"`: Return body stream.
- `type: "blob"`: Return a `Blob`.
- `type: "bytes"`: Return an `Uint8Array`.
- `type: "arrayBuffer"`: Return an `ArrayBuffer` (default)
32 changes: 30 additions & 2 deletions src/drivers/cloudflare-r2-binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,11 @@ export default defineDriver((opts: CloudflareR2Options = {}) => {
const binding = getR2Binding(opts.binding);
return binding.get(key, topts).then((r) => r?.text() ?? null);
},
getItemRaw(key, topts) {
async getItemRaw(key, topts) {
key = r(key);
const binding = getR2Binding(opts.binding);
return binding.get(key, topts).then((r) => r?.arrayBuffer());
const object = await binding.get(key, topts);
return object ? getObjBody(object, topts?.type) : null;
},
async setItem(key, value, topts) {
key = r(key);
Expand Down Expand Up @@ -79,3 +80,30 @@ export default defineDriver((opts: CloudflareR2Options = {}) => {
},
};
});

function getObjBody(
object: R2ObjectBody,
type: "object" | "stream" | "blob" | "arrayBuffer" | "bytes"
) {
switch (type) {
case "object": {
return object;
}
case "stream": {
return object.body;
}
case "blob": {
return object.blob();
}
case "arrayBuffer": {
return object.arrayBuffer();
}
case "bytes": {
return object.arrayBuffer().then((buffer) => new Uint8Array(buffer));
}
// TODO: Default to bytes in v2
default: {
return object.arrayBuffer();
}
}
}
5 changes: 3 additions & 2 deletions test/drivers/cloudflare-r2-binding.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,13 @@ describe("drivers: cloudflare-r2-binding", async () => {
const storageSnapshot = await snapshot(storage, "");

storageSnapshot["base:data:raw.bin"] = (await storage.getItemRaw(
"base:data:raw.bin"
"base:data:raw.bin",
{ type: "bytes" }
)) as any;

expect(storageSnapshot).toMatchInlineSnapshot(`
{
"base:data:raw.bin": ArrayBuffer [
"base:data:raw.bin": Uint8Array [
1,
2,
3,
Expand Down

0 comments on commit 90ae631

Please sign in to comment.