-
Notifications
You must be signed in to change notification settings - Fork 149
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(cloudflare-kv, cloudflare-r2): move
getBindings
to utils a…
…nd add default `BUCKET` for r2 (#292) Co-authored-by: Pooya Parsa <pooya@pi0.io>
- Loading branch information
Showing
4 changed files
with
68 additions
and
79 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/// <reference types="@cloudflare/workers-types" /> | ||
import { createError } from "./index"; | ||
|
||
export function getBinding(binding: KVNamespace | R2Bucket | string) { | ||
let bindingName = "[binding]"; | ||
|
||
if (typeof binding === "string") { | ||
bindingName = binding; | ||
binding = ((globalThis as any)[bindingName] || | ||
(globalThis as any).__env__?.[bindingName]) as KVNamespace | R2Bucket; | ||
} | ||
|
||
if (!binding) { | ||
throw createError( | ||
"cloudflare", | ||
`Invalid binding \`${bindingName}\`: \`${binding}\`` | ||
); | ||
} | ||
|
||
for (const key of ["get", "put", "delete"]) { | ||
if (!(key in binding)) { | ||
throw createError( | ||
"cloudflare", | ||
`Invalid binding \`${bindingName}\`: \`${key}\` key is missing` | ||
); | ||
} | ||
} | ||
|
||
return binding; | ||
} | ||
|
||
export function getKVBinding(binding: KVNamespace | string = "STORAGE") { | ||
return getBinding(binding) as KVNamespace; | ||
} | ||
|
||
export function getR2Binding(binding: R2Bucket | string = "BUCKET") { | ||
return getBinding(binding) as R2Bucket; | ||
} |