rsnext/packages/next/server/web/adapter.ts
Javi Velasco 8752464816
Allow reading request bodies in middlewares (#34294) (#34519)
This PR brings back @Schniz awesome contribution to bring in bodies to middleware. It was reverted to leave it out of the stable release and to have some time to test it out in canary before officially releasing it. This PR is simply a `cherry-pick` of his original work.

Closes: #30953 
Closes: https://github.com/vercel/next.js/pull/34490

Co-authored-by: Gal Schlezinger <2054772+Schniz@users.noreply.github.com>
2022-02-18 19:43:43 +00:00

61 lines
1.7 KiB
TypeScript

import type { NextMiddleware, RequestData, FetchEventResult } from './types'
import type { RequestInit } from './spec-extension/request'
import { DeprecationError } from './error'
import { fromNodeHeaders } from './utils'
import { NextFetchEvent } from './spec-extension/fetch-event'
import { NextRequest } from './spec-extension/request'
import { NextResponse } from './spec-extension/response'
import { waitUntilSymbol } from './spec-compliant/fetch-event'
export async function adapter(params: {
handler: NextMiddleware
page: string
request: RequestData
}): Promise<FetchEventResult> {
const request = new NextRequestHint({
page: params.page,
input: params.request.url,
init: {
body: params.request.body,
geo: params.request.geo,
headers: fromNodeHeaders(params.request.headers),
ip: params.request.ip,
method: params.request.method,
nextConfig: params.request.nextConfig,
page: params.request.page,
},
})
const event = new NextFetchEvent({ request, page: params.page })
const original = await params.handler(request, event)
return {
response: original || NextResponse.next(),
waitUntil: Promise.all(event[waitUntilSymbol]),
}
}
class NextRequestHint extends NextRequest {
sourcePage: string
constructor(params: {
init: RequestInit
input: Request | string
page: string
}) {
super(params.input, params.init)
this.sourcePage = params.page
}
get request() {
throw new DeprecationError({ page: this.sourcePage })
}
respondWith() {
throw new DeprecationError({ page: this.sourcePage })
}
waitUntil() {
throw new DeprecationError({ page: this.sourcePage })
}
}