-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathwithUcanInvocationHandler.js
More file actions
36 lines (31 loc) · 1.26 KB
/
withUcanInvocationHandler.js
File metadata and controls
36 lines (31 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { createServer } from '../server/index.js'
import { createService } from '../server/service.js'
/**
* @import { Middleware } from '@web3-storage/gateway-lib'
* @import {
* Environment,
* Context,
* } from './withUcanInvocationHandler.types.js'
* @typedef {Context} UcanInvocationContext
*/
/**
* The withUcanInvocationHandler middleware is used to handle UCAN invocation requests to the Freeway Gateway.
* It supports only POST requests to the root path. Any other requests are passed through.
*
* @type {Middleware<UcanInvocationContext, UcanInvocationContext, Environment>}
*/
export function withUcanInvocationHandler (handler) {
return async (request, env, ctx) => {
if (request.method !== 'POST' || new URL(request.url).pathname !== '/') {
return handler(request, env, ctx)
}
const service = ctx.service ?? createService(ctx)
const server = ctx.server ?? createServer(ctx, service)
const { headers, body, status } = await server.request({
body: new Uint8Array(await request.arrayBuffer()),
headers: Object.fromEntries(request.headers)
})
// @ts-expect-error - ByteView is compatible with BodyInit but TypeScript doesn't recognize it
return new Response(body, { headers, status: status ?? 200 })
}
}