From 23d8cde6942c051872aa4286b49ee7ee88ee9254 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Thu, 5 May 2022 22:39:38 +0200 Subject: [PATCH] feat: allow explicit middleware handlers --- src/rollup/plugins/handlers.ts | 3 +-- src/runtime/app.ts | 5 +++-- src/runtime/virtual/server-handlers.d.ts | 1 + src/scan.ts | 2 +- src/types/handler.ts | 6 ++++++ 5 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/rollup/plugins/handlers.ts b/src/rollup/plugins/handlers.ts index 0a679e43ec..833fb8f61b 100644 --- a/src/rollup/plugins/handlers.ts +++ b/src/rollup/plugins/handlers.ts @@ -48,10 +48,9 @@ ${imports.map(handler => `import ${getImportId(handler)} from '${handler}';`).jo ${lazyImports.map(handler => `const ${getImportId(handler)} = () => import('${handler}');`).join('\n')} export const handlers = [ -${handlers.map(h => ` { route: '${h.route || ''}', handler: ${getImportId(h.handler)}, lazy: ${h.lazy || true}, method: ${JSON.stringify(h.method)} }`).join(',\n')} +${handlers.map(h => ` { route: '${h.route || ''}', handler: ${getImportId(h.handler)}, lazy: ${h.lazy || true}, middleware: ${!!h.middleware}, method: ${JSON.stringify(h.method)} }`).join(',\n')} ]; `.trim() - // console.log(code) return code } }, nitro.vfs) diff --git a/src/runtime/app.ts b/src/runtime/app.ts index 8b5ae57d0e..de1c5fceb3 100644 --- a/src/runtime/app.ts +++ b/src/runtime/app.ts @@ -45,8 +45,9 @@ function createNitroApp (): NitroApp { }) } - if (h.route === '') { - h3App.use(config.app.baseURL, handler) + if (h.middleware || !h.route) { + const middlewareBase = (config.app.baseURL + (h.route || '/')).replace(/\/+/g, '/') + h3App.use(middlewareBase, handler) } else { router.use(h.route, handler, h.method) } diff --git a/src/runtime/virtual/server-handlers.d.ts b/src/runtime/virtual/server-handlers.d.ts index 00f95097aa..b50ff51234 100644 --- a/src/runtime/virtual/server-handlers.d.ts +++ b/src/runtime/virtual/server-handlers.d.ts @@ -3,6 +3,7 @@ import type { CompatibilityEventHandler, RouterMethod } from 'h3' interface HandlerDefinition { route: string lazy?: boolean + middleware?: boolean handler: CompatibilityEventHandler | (() => Promise) method?: RouterMethod } diff --git a/src/scan.ts b/src/scan.ts index 715bb96be8..94d6b3bc86 100644 --- a/src/scan.ts +++ b/src/scan.ts @@ -23,7 +23,7 @@ export async function scanHandlers (nitro: Nitro) { export function scanMiddleware (nitro: Nitro) { return scanServerDir(nitro, 'middleware', file => ({ - route: '', + middleware: true, handler: file.fullPath })) } diff --git a/src/types/handler.ts b/src/types/handler.ts index da1a9d9bb1..4fdf52f2f3 100644 --- a/src/types/handler.ts +++ b/src/types/handler.ts @@ -8,6 +8,12 @@ export interface NitroEventHandler { */ route?: string + /** + * Specifies this is a middleware handler. + * Middleware are called on every route and should normally return nothing to pass to the next handlers + */ + middleware?: boolean + /** * Use lazy loading to import handler */