feat(middleware/combine): Introduce combine middleware (#2941)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(middleware/predicate): Introduce predicate middleware * fix: apply `bun run format:fix` * refactor: rename middleware predicate -> combine
authored by Taku Amano · committed by GitHub · parent e6d253d · Browse files · 4 files·+421 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+421 added−0 removed
- tests:+264 added−0 removed
- other:+157 added−0 removed
Provenance
- Commit
9a6e52d- Tree
63f134a- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
e6d253d
4 files changed+421 added−0 removed
added:src/middleware/combine/index.test.ts+264 added
1+import { Hono } from '../../hono'2+import { every, except, some } from '.'3+import type { MiddlewareHandler } from '../../types'4+5+const nextMiddleware: MiddlewareHandler = async (_, next) => await next()6+7+describe('some', () => {8+ let app: Hono9+10+ beforeEach(() => {11+ app = new Hono()12+ })13+14+ it('Should call only the first middleware', async () => {15+ const middleware1 = vi.fn(nextMiddleware)16+ const middleware2 = vi.fn(nextMiddleware)17+18+ app.use('/', some(middleware1, middleware2))19+ app.get('/', (c) => {20+ return c.text('Hello World')21+ })22+ const res = await app.request('http://localhost/')23+24+ expect(middleware1).toBeCalled()25+ expect(middleware2).not.toBeCalled()26+ expect(await res.text()).toBe('Hello World')27+ })28+29+ it('Should try to call the second middleware if the first one throws an error', async () => {30+ const middleware1 = () => {31+ throw new Error('Error')32+ }33+ const middleware2 = vi.fn(nextMiddleware)34+35+ app.use('/', some(middleware1, middleware2))36+ app.get('/', (c) => {37+ return c.text('Hello World')38+ })39+ const res = await app.request('http://localhost/')40+41+ expect(middleware2).toBeCalled()42+ expect(await res.text()).toBe('Hello World')43+ })44+45+ it('Should try to call the second middleware if the first one returns false', async () => {46+ const middleware1 = () => false47+ const middleware2 = vi.fn(nextMiddleware)48+49+ app.use('/', some(middleware1, middleware2))50+ app.get('/', (c) => {51+ return c.text('Hello World')52+ })53+ const res = await app.request('http://localhost/')54+55+ expect(middleware2).toBeCalled()56+ expect(await res.text()).toBe('Hello World')57+ })58+59+ it('Should throw last error if all middleware throw an error', async () => {60+ const middleware1 = () => {61+ throw new Error('Error1')62+ }63+ const middleware2 = () => {64+ throw new Error('Error2')65+ }66+67+ app.use('/', some(middleware1, middleware2))68+ app.get('/', (c) => {69+ return c.text('Hello World')70+ })71+ app.onError((error, c) => {72+ return c.text(error.message)73+ })74+ const res = await app.request('http://localhost/')75+76+ expect(await res.text()).toBe('Error2')77+ })78+79+ it('Should throw error if all middleware return false', async () => {80+ const middleware1 = () => false81+ const middleware2 = () => false82+83+ app.use('/', some(middleware1, middleware2))84+ app.get('/', (c) => {85+ return c.text('Hello World')86+ })87+ app.onError((_, c) => {88+ return c.text('oops')89+ })90+ const res = await app.request('http://localhost/')91+92+ expect(await res.text()).toBe('oops')93+ })94+})95+96+describe('every', () => {97+ let app: Hono98+99+ beforeEach(() => {100+ app = new Hono()101+ })102+103+ it('Should call all middleware', async () => {104+ const middleware1 = vi.fn(nextMiddleware)105+ const middleware2 = vi.fn(nextMiddleware)106+107+ app.use('/', every(middleware1, middleware2))108+ app.get('/', (c) => {109+ return c.text('Hello World')110+ })111+ const res = await app.request('http://localhost/')112+113+ expect(middleware1).toBeCalled()114+ expect(middleware2).toBeCalled()115+ expect(await res.text()).toBe('Hello World')116+ })117+118+ it('Should throw error if any middleware throws an error', async () => {119+ const middleware1 = () => {120+ throw new Error('Error1')121+ }122+ const middleware2 = vi.fn(nextMiddleware)123+124+ app.use('/', every(middleware1, middleware2))125+ app.get('/', (c) => {126+ return c.text('Hello World')127+ })128+ app.onError((error, c) => {129+ return c.text(error.message)130+ })131+ const res = await app.request('http://localhost/')132+133+ expect(await res.text()).toBe('Error1')134+ expect(middleware2).not.toBeCalled()135+ })136+137+ it('Should throw error if any middleware returns false', async () => {138+ const middleware1 = () => false139+ const middleware2 = vi.fn(nextMiddleware)140+141+ app.use('/', every(middleware1, middleware2))142+ app.get('/', (c) => {143+ return c.text('Hello World')144+ })145+ app.onError((_, c) => {146+ return c.text('oops')147+ })148+ const res = await app.request('http://localhost/')149+150+ expect(await res.text()).toBe('oops')151+ expect(middleware2).not.toBeCalled()152+ })153+})154+155+describe('except', () => {156+ let app: Hono157+158+ beforeEach(() => {159+ app = new Hono()160+ })161+162+ it('Should call all middleware, except the one that matches the condition', async () => {163+ const middleware1 = vi.fn(nextMiddleware)164+ const middleware2 = vi.fn(nextMiddleware)165+166+ app.use('*', except('/maintenance', middleware1, middleware2))167+ app.get('/maintenance', (c) => {168+ return c.text('Hello Maintenance')169+ })170+ app.get('*', (c) => {171+ return c.redirect('/maintenance')172+ })173+ let res = await app.request('http://localhost/')174+175+ expect(middleware1).toBeCalled()176+ expect(middleware2).toBeCalled()177+ expect(res.headers.get('location')).toBe('/maintenance')178+179+ middleware1.mockClear()180+ middleware2.mockClear()181+ res = await app.request('http://localhost/maintenance')182+183+ expect(middleware1).not.toBeCalled()184+ expect(middleware2).not.toBeCalled()185+ expect(await res.text()).toBe('Hello Maintenance')186+ })187+188+ it('Should call all middleware, except the one that matches some of the conditions', async () => {189+ const middleware1 = vi.fn(nextMiddleware)190+ const middleware2 = vi.fn(nextMiddleware)191+192+ app.use('*', except(['/maintenance', '/public/users/:id'], middleware1, middleware2))193+ app.get('/maintenance', (c) => {194+ return c.text('Hello Maintenance')195+ })196+ app.get('/public/users/:id', (c) => {197+ return c.text(`Hello Public User ${c.req.param('id')}`)198+ })199+ app.get('/secret', (c) => {200+ return c.text('Hello Secret')201+ })202+ let res = await app.request('http://localhost/secret')203+204+ expect(middleware1).toBeCalled()205+ expect(middleware2).toBeCalled()206+ expect(await res.text()).toBe('Hello Secret')207+208+ middleware1.mockClear()209+ middleware2.mockClear()210+ res = await app.request('http://localhost/maintenance')211+212+ expect(middleware1).not.toBeCalled()213+ expect(middleware2).not.toBeCalled()214+ expect(await res.text()).toBe('Hello Maintenance')215+216+ middleware1.mockClear()217+ middleware2.mockClear()218+ res = await app.request('http://localhost/public/users/123')219+220+ expect(middleware1).not.toBeCalled()221+ expect(middleware2).not.toBeCalled()222+ expect(await res.text()).toBe('Hello Public User 123')223+ })224+225+ it('Should call all middleware, except the one that matches some of the condition function', async () => {226+ const middleware1 = vi.fn(nextMiddleware)227+ const middleware2 = vi.fn(nextMiddleware)228+229+ app.use(230+ '*',231+ except(['/maintenance', (c) => !!c.req.path.match(/public/)], middleware1, middleware2)232+ )233+ app.get('/maintenance', (c) => {234+ return c.text('Hello Maintenance')235+ })236+ app.get('/public/users/:id', (c) => {237+ return c.text(`Hello Public User ${c.req.param('id')}`)238+ })239+ app.get('/secret', (c) => {240+ return c.text('Hello Secret')241+ })242+ let res = await app.request('http://localhost/secret')243+244+ expect(middleware1).toBeCalled()245+ expect(middleware2).toBeCalled()246+ expect(await res.text()).toBe('Hello Secret')247+248+ middleware1.mockClear()249+ middleware2.mockClear()250+ res = await app.request('http://localhost/maintenance')251+252+ expect(middleware1).not.toBeCalled()253+ expect(middleware2).not.toBeCalled()254+ expect(await res.text()).toBe('Hello Maintenance')255+256+ middleware1.mockClear()257+ middleware2.mockClear()258+ res = await app.request('http://localhost/public/users/123')259+260+ expect(middleware1).not.toBeCalled()261+ expect(middleware2).not.toBeCalled()262+ expect(await res.text()).toBe('Hello Public User 123')263+ })264+})added:src/middleware/combine/index.ts+148 added
1+import type { Context } from '../../context'2+import type { MiddlewareHandler, Next } from '../../types'3+import { TrieRouter } from '../../router/trie-router'4+import { METHOD_NAME_ALL } from '../../router'5+import { compose } from '../../compose'6+7+type Condition = (c: Context) => boolean8+9+/**10+ * Create a composed middleware that runs the first middleware that returns true.11+ *12+ * @param middleware - An array of MiddlewareHandler or Condition functions.13+ * Middleware is applied in the order it is passed, and if any middleware exits without returning14+ * an exception first, subsequent middleware will not be executed.15+ * You can also pass a condition function that returns a boolean value. If returns true16+ * the evaluation will be halted, and rest of the middleware will not be executed.17+ * @returns A composed middleware.18+ *19+ * @example20+ * ```ts21+ * import { some } from 'combine'22+ * import { bearerAuth } from 'bearer-auth'23+ * import { myRateLimit } from '@/rate-limit'24+ *25+ * // If client has a valid token, then skip rate limiting.26+ * // Otherwise, apply rate limiting.27+ * app.use('/api/*', some(28+ * bearerAuth({ token }),29+ * myRateLimit({ limit: 100 }),30+ * ));31+ * ```32+ */33+export const some = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => {34+ return async function some(c, next) {35+ let lastError: unknown36+ for (const handler of middleware) {37+ try {38+ const result = await handler(c, next)39+ if (result === true && !c.finalized) {40+ await next()41+ } else if (result === false) {42+ lastError = new Error('No successful middleware found')43+ continue44+ }45+ lastError = undefined46+ break47+ } catch (error) {48+ lastError = error49+ continue50+ }51+ }52+ if (lastError) {53+ throw lastError54+ }55+ }56+}57+58+/**59+ * Create a composed middleware that runs all middleware and throws an error if any of them fail.60+ *61+ * @param middleware - An array of MiddlewareHandler or Condition functions.62+ * Middleware is applied in the order it is passed, and if any middleware throws an error,63+ * subsequent middleware will not be executed.64+ * You can also pass a condition function that returns a boolean value. If returns false65+ * the evaluation will be halted, and rest of the middleware will not be executed.66+ * @returns A composed middleware.67+ *68+ * @example69+ * ```ts70+ * import { some, every } from 'combine'71+ * import { bearerAuth } from 'bearer-auth'72+ * import { myCheckLocalNetwork } from '@/check-local-network'73+ * import { myRateLimit } from '@/rate-limit'74+ *75+ * // If client is in local network, then skip authentication and rate limiting.76+ * // Otherwise, apply authentication and rate limiting.77+ * app.use('/api/*', some(78+ * myCheckLocalNetwork(),79+ * every(80+ * bearerAuth({ token }),81+ * myRateLimit({ limit: 100 }),82+ * ),83+ * ));84+ * ```85+ */86+export const every = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => {87+ const wrappedMiddleware = middleware.map((m) => async (c: Context, next: Next) => {88+ const res = await m(c, next)89+ if (res === false) {90+ throw new Error('Unmet condition')91+ }92+ })93+94+ const handler = async (c: Context, next: Next) =>95+ compose<Context>(wrappedMiddleware.map((m) => [[m, undefined], c.req.param()]))(c, next)96+97+ return async function every(c, next) {98+ await handler(c, next)99+ }100+}101+102+/**103+ * Create a composed middleware that runs all middleware except when the condition is met.104+ *105+ * @param condition - A string or Condition function.106+ * If there are multiple targets to match any of them, they can be passed as an array.107+ * If a string is passed, it will be treated as a path pattern to match.108+ * If a Condition function is passed, it will be evaluated against the request context.109+ * @param middleware - A composed middleware110+ *111+ * @example112+ * ```ts113+ * import { except } from 'combine'114+ * import { bearerAuth } from 'bearer-auth115+ *116+ * // If client is accessing public API, then skip authentication.117+ * // Otherwise, require a valid token.118+ * app.use('/api/*', except(119+ * '/api/public/*',120+ * bearerAuth({ token }),121+ * ));122+ * ```123+ */124+export const except = (125+ condition: string | Condition | (string | Condition)[],126+ ...middleware: MiddlewareHandler[]127+): MiddlewareHandler => {128+ let router: TrieRouter<true> | undefined = undefined129+ const conditions = (Array.isArray(condition) ? condition : [condition])130+ .map((condition) => {131+ if (typeof condition === 'string') {132+ router ||= new TrieRouter()133+ router.add(METHOD_NAME_ALL, condition, true)134+ } else {135+ return condition136+ }137+ })138+ .filter(Boolean) as Condition[]139+140+ if (router) {141+ conditions.unshift((c: Context) => !!router?.match(METHOD_NAME_ALL, c.req.path)?.[0]?.[0]?.[0])142+ }143+144+ const handler = some((c: Context) => conditions.some((cond) => cond(c)), every(...middleware))145+ return async function except(c, next) {146+ await handler(c, next)147+ }148+}modified:jsr.json+1 added
49 unmodified lines50515253545556575860 unmodified lines49 unmodified lines "./powered-by": "./src/middleware/powered-by/index.ts", "./pretty-json": "./src/middleware/pretty-json/index.ts", "./request-id": "./src/middleware/request-id/request-id.ts", "./secure-headers": "./src/middleware/secure-headers/secure-headers.ts", "./combine": "./src/middleware/combine/index.ts", "./ssg": "./src/helper/ssg/index.ts", "./streaming": "./src/helper/streaming/index.ts", "./validator": "./src/validator/index.ts", "./router": "./src/router.ts",60 unmodified linesmodified:package.json+8 added
231 unmodified lines232 "types": "./dist/types/middleware/secure-headers/index.d.ts",233 "import": "./dist/middleware/secure-headers/index.js",234 "require": "./dist/cjs/middleware/secure-headers/index.js"235 },236+ "./combine": {237+ "types": "./dist/types/middleware/combine/index.d.ts",238+ "import": "./dist/middleware/combine/index.js",239+ "require": "./dist/cjs/middleware/combine/index.js"240+ },241 "./ssg": {242 "types": "./dist/types/helper/ssg/index.d.ts",243 "import": "./dist/helper/ssg/index.js",244 "require": "./dist/cjs/helper/ssg/index.js"252 unmodified lines497 ],498 "secure-headers": [499 "./dist/types/middleware/secure-headers"500 ],501+ "combine": [502+ "./dist/types/middleware/combine"503+ ],504 "validator": [505 "./dist/types/validator/index.d.ts"506 ],507 "router": [135 unmodified lines