Skip to content

Commit

Permalink
feat: allow explicit middleware handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed May 5, 2022
1 parent 45f48a3 commit 23d8cde
Show file tree
Hide file tree
Showing 5 changed files with 12 additions and 5 deletions.
3 changes: 1 addition & 2 deletions src/rollup/plugins/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions src/runtime/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
1 change: 1 addition & 0 deletions src/runtime/virtual/server-handlers.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { CompatibilityEventHandler, RouterMethod } from 'h3'
interface HandlerDefinition {
route: string
lazy?: boolean
middleware?: boolean
handler: CompatibilityEventHandler | (() => Promise<CompatibilityEventHandler>)
method?: RouterMethod
}
Expand Down
2 changes: 1 addition & 1 deletion src/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}))
}
Expand Down
6 changes: 6 additions & 0 deletions src/types/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down

0 comments on commit 23d8cde

Please sign in to comment.