Skip to content

Commit

Permalink
feat(nitro): handle request body in workers (#537)
Browse files Browse the repository at this point in the history
  • Loading branch information
farnabaz authored Sep 20, 2021
1 parent 2298276 commit c3249cb
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
5 changes: 5 additions & 0 deletions src/runtime/entries/cloudflare.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import '#polyfill'
import { getAssetFromKV } from '@cloudflare/kv-asset-handler'
import { localCall } from '../server'
import { requestHasBody, useRequestBody } from '../server/utils'

const PUBLIC_PATH = process.env.PUBLIC_PATH // Default: /_nuxt/

Expand All @@ -17,6 +18,10 @@ async function handleEvent (event) {

const url = new URL(event.request.url)

if (requestHasBody(event.request)) {
event.request.body = await useRequestBody(event.request)
}

const r = await localCall({
event,
url: url.pathname + url.search,
Expand Down
7 changes: 4 additions & 3 deletions src/runtime/entries/service-worker.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// @ts-nocheck
import '#polyfill'
import { localCall } from '../server'
import { requestHasBody, useRequestBody } from '../server/utils'

const STATIC_ASSETS_BASE = process.env.NUXT_STATIC_BASE + '/' + process.env.NUXT_STATIC_VERSION
const METHODS_WITH_BODY = ['POST', 'PUT', 'PATCH']

addEventListener('fetch', (event: any) => {
const url = new URL(event.request.url)
Expand All @@ -16,9 +16,10 @@ addEventListener('fetch', (event: any) => {
})

async function handleEvent (url, event) {
if (METHODS_WITH_BODY.includes(event.request.method.toUpperCase()) && !event.request.body) {
event.request.body = await event.request.text()
if (requestHasBody(event.request)) {
event.request.body = await useRequestBody(event.request)
}

const r = await localCall({
event,
url: url.pathname + url.search,
Expand Down
26 changes: 26 additions & 0 deletions src/runtime/server/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const METHOD_WITH_BODY_RE = /post|put|patch/i
const TEXT_MIME_RE = /application\/text|text\/html/
const JSON_MIME_RE = /application\/json/

export function requestHasBody (request: globalThis.Request) : boolean {
return METHOD_WITH_BODY_RE.test(request.method)
}

export async function useRequestBody (request: globalThis.Request): Promise<any> {
const contentType = request.headers.get('content-type') || ''
if (contentType.includes('form')) {
const formData = await request.formData()
const body = Object.create(null)
for (const entry of formData.entries()) {
body[entry[0]] = entry[1]
}
return body
} else if (JSON_MIME_RE.test(contentType)) {
return request.json()
} else if (TEXT_MIME_RE.test(contentType)) {
return request.text()
} else {
const blob = await request.blob()
return URL.createObjectURL(blob)
}
}

0 comments on commit c3249cb

Please sign in to comment.