-
-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
12 additions
and
26 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,17 @@ | ||
import { StatusError } from 'itty-router' | ||
import { proxyDurable } from './proxy-durable' | ||
const withDO = (request: any, env: any) => { | ||
request.DO = new Proxy(request.proxy ?? request, { | ||
get: (target: Request, prop: string, receiver) => { | ||
// @ts-ignore | ||
if (target[prop] != undefined) return target[prop] | ||
|
||
// returns true if binding appears to be a durable binding | ||
const isDurable = (binding) => typeof binding.idFromName === 'function' | ||
const DO = env[prop], isDO = DO?.idFromName | ||
if (!isDO) return undefined | ||
|
||
export const withDurables = (options = {}) => (request, env) => { | ||
const { | ||
parse = false, | ||
classes = {}, | ||
} = options | ||
request.durables = request.durables || {} | ||
|
||
for (const [key, binding] of Object.entries(env)) { | ||
if (isDurable(binding)) { | ||
const proxied = proxyDurable(binding, { | ||
name: key, | ||
class: classes[key], // pass in class key by default, | ||
headers: Object.fromEntries(request.headers), | ||
env, | ||
parse, | ||
}) | ||
|
||
try { | ||
request[key] = request.durables[key] = proxied | ||
} catch (err) { | ||
throw new StatusError(500, `Could not set Durable binding "${key}" on Request`) | ||
return (id: any) => | ||
typeof id == 'string' | ||
? DO.get(DO.idFromName(id)) | ||
: DO.get(id) | ||
} | ||
} | ||
} | ||
) | ||
} |