-
Notifications
You must be signed in to change notification settings - Fork 501
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(nitro): handle request body in workers (#537)
- Loading branch information
Showing
3 changed files
with
35 additions
and
3 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
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) | ||
} | ||
} |