body.ts
This file
Path
src/utils/body.ts
263 lines 路 7.7 KiB 路 TypeScript
Last changed by
Merge commit from forkTaku Amanobefore adoption531e9c5
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264/** * @module * Body utility. */
import type { HonoRequest } from '../request'import { bufferToFormData } from './buffer'
const MAX_NESTING_DEPTH = 32const MAX_NESTED_OBJECTS = 10_000
type BodyDataValueDot = { [x: string]: string | File | BodyDataValueDot }type BodyDataValueDotAll = { [x: string]: string | File | (string | File)[] | BodyDataValueDotAll}type SimplifyBodyData<T> = { [K in keyof T]: string | File | (string | File)[] | BodyDataValueDotAll extends T[K] ? string | File | (string | File)[] | BodyDataValueDotAll : string | File | BodyDataValueDot extends T[K] ? string | File | BodyDataValueDot : string | File | (string | File)[] extends T[K] ? string | File | (string | File)[] : string | File} & {}
type BodyDataValueComponent<T> = | string | File | (T extends { all: false } ? never // explicitly set to false : T extends { all: true } | { all: boolean } ? (string | File)[] // use all option : never) // without optionstype BodyDataValueObject<T> = { [key: string]: BodyDataValueComponent<T> | BodyDataValueObject<T> }type BodyDataValue<T> = | BodyDataValueComponent<T> | (T extends { dot: false } ? never // explicitly set to false : T extends { dot: true } | { dot: boolean } ? BodyDataValueObject<T> // use dot option : never) // without optionsexport type BodyData<T extends Partial<ParseBodyOptions> = {}> = SimplifyBodyData< Record<string, BodyDataValue<T>>>
export type ParseBodyOptions = { /** * Determines whether all fields with multiple values should be parsed as arrays. * @default false * @example * const data = new FormData() * data.append('file', 'aaa') * data.append('file', 'bbb') * data.append('message', 'hello') * * If all is false: * parseBody should return { file: 'bbb', message: 'hello' } * * If all is true: * parseBody should return { file: ['aaa', 'bbb'], message: 'hello' } */ all: boolean /** * Determines whether all fields with dot notation should be parsed as nested objects. * @default false * @example * const data = new FormData() * data.append('obj.key1', 'value1') * data.append('obj.key2', 'value2') * * If dot is false: * parseBody should return { 'obj.key1': 'value1', 'obj.key2': 'value2' } * * If dot is true: * parseBody should return { obj: { key1: 'value1', key2: 'value2' } } */ dot: boolean}
const isRawRequest = (request: HonoRequest | Request): request is Request => 'headers' in request // 'headers' method exists only on Request, not on HonoRequest.
/** * Parses the body of a request based on the provided options. * * @template T - The type of the parsed body data. * @param {HonoRequest | Request} request - The request object to parse. * @param {Partial<ParseBodyOptions>} [options] - Options for parsing the body. * @returns {Promise<T>} The parsed body data. */interface ParseBody { <Options extends Partial<ParseBodyOptions>, T extends BodyData<Options>>( request: HonoRequest | Request, options?: Options ): Promise<T> <T extends BodyData>( request: HonoRequest | Request, options?: Partial<ParseBodyOptions> ): Promise<T>}export const parseBody: ParseBody = async ( request: HonoRequest | Request, options = Object.create(null)) => { const { all = false, dot = false } = options
const headers = isRawRequest(request) ? request.headers : request.raw.headers const contentType = headers.get('Content-Type')
const mediaType = contentType?.split(';')[0].trim().toLowerCase()
if (mediaType === 'multipart/form-data' || mediaType === 'application/x-www-form-urlencoded') { return parseFormData(request, { all, dot }) }
return {}}
/** * Parses form data from a request. * * @template T - The type of the parsed body data. * @param {HonoRequest | Request} request - The request object containing form data. * @param {ParseBodyOptions} options - Options for parsing the form data. * @returns {Promise<T>} The parsed body data. */async function parseFormData<T extends BodyData>( request: HonoRequest | Request, options: ParseBodyOptions): Promise<T> { if (!isRawRequest(request) && request.bodyCache.formData) { return convertFormDataToBodyData<T>( await (request.bodyCache.formData as FormData | Promise<FormData>), options ) } const headers = isRawRequest(request) ? request.headers : request.raw.headers const arrayBuffer = await (request as Request).arrayBuffer() const formDataPromise = bufferToFormData(arrayBuffer, headers.get('Content-Type') || '') if (!isRawRequest(request)) { // Cache so that a later `c.req.formData()` reuses the already-consumed body request.bodyCache.formData = formDataPromise as unknown as FormData } const formData = await formDataPromise
if (formData) { return convertFormDataToBodyData<T>(formData, options) }
return {} as T}
/** * Converts form data to body data based on the provided options. * * @template T - The type of the parsed body data. * @param {FormData} formData - The form data to convert. * @param {ParseBodyOptions} options - Options for parsing the form data. * @returns {T} The converted body data. */function convertFormDataToBodyData<T extends BodyData = BodyData>( formData: FormData, options: ParseBodyOptions): T { const form: BodyData = Object.create(null) const nestingState = { count: 0 }
formData.forEach((value, key) => { const shouldParseAllValues = options.all || key.endsWith('[]')
if (!shouldParseAllValues) { form[key] = value } else { handleParsingAllValues(form, key, value) } })
if (options.dot) { Object.entries(form).forEach(([key, value]) => { const shouldParseDotValues = key.includes('.')
if (shouldParseDotValues) { handleParsingNestedValues(form, key, value, nestingState) delete form[key] } }) }
return form as T}
/** * Handles parsing all values for a given key, supporting multiple values as arrays. * * @param {BodyData} form - The form data object. * @param {string} key - The key to parse. * @param {FormDataEntryValue} value - The value to assign. */const handleParsingAllValues = ( form: BodyData<{ all: true }>, key: string, value: FormDataEntryValue): void => { if (form[key] !== undefined) { if (Array.isArray(form[key])) { ;(form[key] as (string | File)[]).push(value) } else { form[key] = [form[key] as string | File, value] } } else { if (!key.endsWith('[]')) { form[key] = value } else { form[key] = [value] } }}
/** * Handles parsing nested values using dot notation keys. * * @param {BodyData} form - The form data object. * @param {string} key - The dot notation key. * @param {BodyDataValue} value - The value to assign. */const handleParsingNestedValues = ( form: BodyData, key: string, value: BodyDataValue<Partial<ParseBodyOptions>>, state: { count: number }): void => { if (/(?:^|\.)__proto__\./.test(key)) { return }
let nestedForm = form const keys = key.split('.', MAX_NESTING_DEPTH + 2) if (keys.length > MAX_NESTING_DEPTH + 1) { throwNestingLimitExceeded() }
keys.forEach((key, index) => { if (index === keys.length - 1) { nestedForm[key] = value } else { if ( !nestedForm[key] || typeof nestedForm[key] !== 'object' || Array.isArray(nestedForm[key]) || nestedForm[key] instanceof File ) { if (state.count++ >= MAX_NESTED_OBJECTS) { throwNestingLimitExceeded() } nestedForm[key] = Object.create(null) } nestedForm = nestedForm[key] as unknown as BodyData } })}
const throwNestingLimitExceeded = (): never => { throw new Error('Nesting limit exceeded')}