index.ts
This file
Path
src/middleware/combine/index.ts
171 lines · 5.4 KiB · TypeScript
Last changed by
fix(combine): return a Response from a short-circuiting middleware in some() (#5391)Harshit Prakashbefore adoptionafb2068
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–46why, one step back1/**2 * @module3 * Combine Middleware for Hono.4 */56import { compose } from '../../compose'7import type { Context } from '../../context'8import { METHOD_NAME_ALL } from '../../router'9import { TrieRouter } from '../../router/trie-router'10import type { MiddlewareHandler, Next } from '../../types'1112type Condition = (c: Context) => boolean1314/**15 * Create a composed middleware that runs the first middleware that returns true.16 *17 * @param middleware - An array of MiddlewareHandler or Condition functions.18 * Middleware is applied in the order it is passed, and if any middleware exits without returning19 * an exception first, subsequent middleware will not be executed.20 * You can also pass a condition function that returns a boolean value. If returns true21 * the evaluation will be halted, and rest of the middleware will not be executed.22 * @returns A composed middleware.23 *24 * @example25 * ```ts26 * import { some } from 'hono/combine'27 * import { bearerAuth } from 'hono/bearer-auth'28 * import { myRateLimit } from '@/rate-limit'29 *30 * // If client has a valid token, then skip rate limiting.31 * // Otherwise, apply rate limiting.32 * app.use('/api/*', some(33 * bearerAuth({ token }),34 * myRateLimit({ limit: 100 }),35 * ));36 * ```37 */38export const some = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => {39 return async function some(c, next) {40 let isNextCalled = false41 const wrappedNext = () => {42 isNextCalled = true43 return next()44 }4546 let lastError: unknownfix(combine): return a Response from a short-circuiting middleware in some() (#5391)Harshit Prakashbefore adoptionafb2068
line 47why, one step back47 let response: Response | undefinedMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 48–55why, one step back48 for (const handler of middleware) {49 try {50 const result = await handler(c, wrappedNext)51 if (result === true && !c.finalized) {52 await wrappedNext()53 } else if (result === false) {54 lastError = new Error('No successful middleware found')55 continuefix(combine): return a Response from a short-circuiting middleware in some() (#5391)Harshit Prakashbefore adoptionafb2068
lines 56–57why, one step back56 } else if (result && result !== true) {57 response = resultMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 58–70why, one step back58 }59 lastError = undefined60 break61 } catch (error) {62 lastError = error63 if (isNextCalled) {64 break65 }66 }67 }68 if (lastError) {69 throw lastError70 }fix(combine): return a Response from a short-circuiting middleware in some() (#5391)Harshit Prakashbefore adoptionafb2068
line 71why, one step back71 return responseMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 72–129why, one step back72 }73}7475/**76 * Create a composed middleware that runs all middleware and throws an error if any of them fail.77 *78 * @param middleware - An array of MiddlewareHandler or Condition functions.79 * Middleware is applied in the order it is passed, and if any middleware throws an error,80 * subsequent middleware will not be executed.81 * You can also pass a condition function that returns a boolean value. If returns false82 * the evaluation will be halted, and rest of the middleware will not be executed.83 * @returns A composed middleware.84 *85 * @example86 * ```ts87 * import { some, every } from 'hono/combine'88 * import { bearerAuth } from 'hono/bearer-auth'89 * import { myCheckLocalNetwork } from '@/check-local-network'90 * import { myRateLimit } from '@/rate-limit'91 *92 * // If client is in local network, then skip authentication and rate limiting.93 * // Otherwise, apply authentication and rate limiting.94 * app.use('/api/*', some(95 * myCheckLocalNetwork(),96 * every(97 * bearerAuth({ token }),98 * myRateLimit({ limit: 100 }),99 * ),100 * ));101 * ```102 */103export const every = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => {104 return async function every(c, next) {105 const currentRouteIndex = c.req.routeIndex106 await compose(107 middleware.map((m) => [108 [109 async (c: Context, next: Next) => {110 c.req.routeIndex = currentRouteIndex // should be unchanged in this context111 const res = await m(c, next)112 if (res === false) {113 throw new Error('Unmet condition')114 }115 return res116 },117 ],118 ])119 )(c, next)120 }121}122123/**124 * Create a composed middleware that runs all middleware except when the condition is met.125 *126 * @param condition - A string or Condition function.127 * If there are multiple targets to match any of them, they can be passed as an array.128 * If a string is passed, it will be treated as a path pattern to match.129 * If a Condition function is passed, it will be evaluated against the request context.docs(combine): fix except() JSDoc param and add missing @returns (#5346)Aidanbefore adoption8755b17
lines 130–132why, one step back130 * @param middleware - Middleware to run when the condition is not met.131 * Multiple middleware can be passed, and they are applied in the order they are passed.132 * @returns A composed middleware.Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 133–136why, one step back133 *134 * @example135 * ```ts136 * import { except } from 'hono/combine'docs(combine): close quote in combine JSDoc example (#5126)Kriday Davebefore adoption5f73897
line 137why, one step back137 * import { bearerAuth } from 'hono/bearer-auth'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 138–171why, one step back138 *139 * // If client is accessing public API, then skip authentication.140 * // Otherwise, require a valid token.141 * app.use('/api/*', except(142 * '/api/public/*',143 * bearerAuth({ token }),144 * ));145 * ```146 */147export const except = (148 condition: string | Condition | (string | Condition)[],149 ...middleware: MiddlewareHandler[]150): MiddlewareHandler => {151 let router: TrieRouter<true> | undefined = undefined152 const conditions = (Array.isArray(condition) ? condition : [condition])153 .map((condition) => {154 if (typeof condition === 'string') {155 router ||= new TrieRouter()156 router.add(METHOD_NAME_ALL, condition, true)157 } else {158 return condition159 }160 })161 .filter(Boolean) as Condition[]162163 if (router) {164 conditions.unshift((c: Context) => !!router?.match(METHOD_NAME_ALL, c.req.path)?.[0]?.[0]?.[0])165 }166167 const handler = some((c: Context) => conditions.some((cond) => cond(c)), every(...middleware))168 return async function except(c, next) {169 await handler(c, next)170 }171}