index.ts
This file
Path
src/middleware/method-override/index.ts
148 lines · 4.6 KiB · TypeScript
Last changed by
fix(method-override): set duplex when forwarding a stream body in query mode (#5110)Yusuke Wadabefore adoptione0cdeb0
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–126why, one step back1/**2 * @module3 * Method Override Middleware for Hono.4 */56import type { Context, ExecutionContext } from '../../context'7import type { Hono } from '../../hono'8import type { MiddlewareHandler } from '../../types'9import { parseBody } from '../../utils/body'1011type MethodOverrideOptions = {12 // eslint-disable-next-line @typescript-eslint/no-explicit-any13 app: Hono<any, any, any>14} & (15 | {16 // Default is 'form' and the value is `_method`17 form?: string18 header?: never19 query?: never20 }21 | {22 form?: never23 header: string24 query?: never25 }26 | {27 form?: never28 header?: never29 query: string30 }31)3233const DEFAULT_METHOD_FORM_NAME = '_method'3435/**36 * Method Override Middleware for Hono.37 *38 * @see {@link https://hono.dev/docs/middleware/builtin/method-override}39 *40 * @param {MethodOverrideOptions} options - The options for the method override middleware.41 * @param {Hono} options.app - The instance of Hono is used in your application.42 * @param {string} [options.form=_method] - Form key with a value containing the method name.43 * @param {string} [options.header] - Header name with a value containing the method name.44 * @param {string} [options.query] - Query parameter key with a value containing the method name.45 * @returns {MiddlewareHandler} The middleware handler function.46 *47 * @example48 * ```ts49 * const app = new Hono()50 *51 * // If no options are specified, the value of `_method` in the form,52 * // e.g. DELETE, is used as the method.53 * app.use('/posts', methodOverride({ app }))54 *55 * app.delete('/posts', (c) => {56 * // ....57 * })58 * ```59 */60export const methodOverride = (options: MethodOverrideOptions): MiddlewareHandler =>61 async function methodOverride(c, next) {62 if (c.req.method === 'GET') {63 return await next()64 }6566 const app = options.app67 // Method override by form68 if (!(options.header || options.query)) {69 const contentType = c.req.header('content-type')70 const methodFormName = options.form || DEFAULT_METHOD_FORM_NAME71 const clonedRequest = c.req.raw.clone()72 const newRequest = clonedRequest.clone()73 // Content-Type is `multipart/form-data`74 if (contentType?.startsWith('multipart/form-data')) {75 const form = await clonedRequest.formData()76 const method = form.get(methodFormName)77 if (method) {78 const newForm = await newRequest.formData()79 newForm.delete(methodFormName)80 const newHeaders = new Headers(clonedRequest.headers)81 newHeaders.delete('content-type')82 newHeaders.delete('content-length')83 const request = new Request(c.req.url, {84 body: newForm,85 headers: newHeaders,86 method: method as string,87 })88 return app.fetch(request, c.env, getExecutionCtx(c))89 }90 }91 // Content-Type is `application/x-www-form-urlencoded`92 if (contentType?.startsWith('application/x-www-form-urlencoded')) {93 const params = await parseBody<Record<string, string>>(clonedRequest)94 const method = params[methodFormName]95 if (method) {96 delete params[methodFormName]97 const newParams = new URLSearchParams(params)98 const request = new Request(newRequest, {99 body: newParams,100 method: method as string,101 })102 return app.fetch(request, c.env, getExecutionCtx(c))103 }104 }105 }106 // Method override by header107 else if (options.header) {108 const headerName = options.header109 const method = c.req.header(headerName)110 if (method) {111 const newHeaders = new Headers(c.req.raw.headers)112 newHeaders.delete(headerName)113 const request = new Request(c.req.raw, {114 headers: newHeaders,115 method,116 })117 return app.fetch(request, c.env, getExecutionCtx(c))118 }119 }120 // Method override by query121 else if (options.query) {122 const queryName = options.query123 const method = c.req.query(queryName)124 if (method) {125 const url = new URL(c.req.url)126 url.searchParams.delete(queryName)fix(method-override): set duplex when forwarding a stream body in query mode (#5110)Yusuke Wadabefore adoptione0cdeb0
line 127why, one step back127 const requestInit: RequestInit & { duplex?: 'half' } = {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 128–130why, one step back128 body: c.req.raw.body,129 headers: c.req.raw.headers,130 method,fix(method-override): set duplex when forwarding a stream body in query mode (#5110)Yusuke Wadabefore adoptione0cdeb0
lines 131–133why, one step back131 duplex: c.req.raw.body ? 'half' : undefined,132 }133 const request = new Request(url.toString(), requestInit)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 134–148why, one step back134 return app.fetch(request, c.env, getExecutionCtx(c))135 }136 }137 await next()138 }139140const getExecutionCtx = (c: Context) => {141 let executionCtx: ExecutionContext | undefined142 try {143 executionCtx = c.executionCtx144 } catch {145 // Do nothing146 }147 return executionCtx148}