Skip to content
Myr

index.ts

This file

Path

src/middleware/method-not-allowed/index.ts

141 lines · 4.4 KiB · TypeScript

Last changed by

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

History of this file

Take it

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 1–141why, one step back
1/**
2 * @module3 * Method Not Allowed Middleware for Hono.4 */56import type { Context } from '../../context'7import { basePath, matchedRoutes } from '../../helper/route'8import type { Hono } from '../../hono'9import { METHOD_NAME_ALL } from '../../router'10import { TrieRouter } from '../../router/trie-router'11import type { Env, MiddlewareHandler } from '../../types'1213type MethodNotAllowedHandler<E extends Env> = (14 c: Context<E>,15 allowedMethods: string[]16) => Response | Promise<Response>1718type MethodNotAllowedOptions<E extends Env> = {19 // eslint-disable-next-line @typescript-eslint/no-explicit-any20 app: Hono<E, any, any>21 onMethodNotAllowed?: MethodNotAllowedHandler<E>22}2324/**25 * Method Not Allowed Middleware for Hono.26 *27 * Returns a `405 Method Not Allowed` response with an `Allow` header when the request path28 * matches a registered route but the request method is not supported.29 *30 * @param {MethodNotAllowedOptions} options - The options for the middleware.31 * @param {Hono} options.app - The Hono instance used by the application.32 * @param {MethodNotAllowedHandler} [options.onMethodNotAllowed] - Generates the response, including its `Allow` header.33 * @returns {MiddlewareHandler} The middleware handler function.34 *35 * @example36 * ```ts37 * const app = new Hono()38 *39 * app.use(methodNotAllowed({ app }))40 *41 * app.get('/hello', (c) => c.text('Hello!'))42 * app.post('/hello', (c) => c.text('Posted!'))43 *44 * // PUT /hello -> 405 Method Not Allowed45 * // Allow: GET, HEAD, POST46 * ```47 *48 * @example49 * ```ts50 * app.use(51 * methodNotAllowed({52 * app,53 * onMethodNotAllowed: (c, methods) =>54 * c.json({ error: 'Method Not Allowed' }, 405, { Allow: methods.join(', ') }),55 * })56 * )57 * ```58 */59export const methodNotAllowed = <E extends Env = Env>(60 options: MethodNotAllowedOptions<E>61): MiddlewareHandler<E> => {62 let methodRouter: TrieRouter<string[]> | undefined6364 return async function methodNotAllowed(c, next) {65 const routeIndex = c.req.routeIndex66 await next()6768 if (c.res.status !== 404) {69 return70 }7172 if (c.error) {73 return74 }7576 if (!methodRouter) {77 const methodsByPath = new Map<string, Set<string>>()7879 for (const route of options.app.routes) {80 // Hono does not distinguish middleware registered with `app.use()` from handlers81 // registered with `app.all()`, so `ALL` routes cannot contribute to the Allow header.82 if (route.method === METHOD_NAME_ALL || route.method === 'HEAD') {83 continue84 }8586 const methods = methodsByPath.get(route.path) ?? new Set<string>()87 methods.add(route.method)8889 // Hono dispatches HEAD requests to GET routes.90 if (route.method === 'GET') {91 methods.add('HEAD')92 }9394 methodsByPath.set(route.path, methods)95 }9697 methodRouter = new TrieRouter()98 for (const [path, methods] of methodsByPath) {99 methodRouter.add(METHOD_NAME_ALL, path, [...methods])100 }101 }102103 let requestPath = c.req.path104 const routes = matchedRoutes(c)105 const currentRoute = routes[routeIndex]106 const sourceRoute = options.app.routes.find((route) => route.handler === methodNotAllowed)107 if (currentRoute && sourceRoute) {108 const currentBasePathParts = basePath(c, routeIndex).split('/').filter(Boolean)109 const sourceBasePathLength = sourceRoute.basePath.split('/').filter(Boolean).length110 const mountBasePathParts = currentBasePathParts.slice(111 0,112 currentBasePathParts.length - sourceBasePathLength113 )114 if (mountBasePathParts.length > 0) {115 const mountBasePath = `/${mountBasePathParts.join('/')}`116 requestPath = c.req.path.slice(mountBasePath.length) || '/'117 }118 }119120 const allowedMethods = new Set<string>()121 for (const [methods] of methodRouter.match(METHOD_NAME_ALL, requestPath)[0]) {122 for (const method of methods) {123 allowedMethods.add(method)124 }125 }126127 if (allowedMethods.size === 0 || allowedMethods.has(c.req.method)) {128 return129 }130131 // Prevent stale headers from being carried over from the 404 response.132 c.res.headers.delete('Allow')133 c.res.headers.delete('Content-Length')134135 const methods = [...allowedMethods]136 const allow = methods.join(', ')137 c.res = options.onMethodNotAllowed138 ? await options.onMethodNotAllowed(c, methods)139 : c.text('Method Not Allowed', 405, { Allow: allow })140 }141}