mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-25 23:22:02 +00:00
feat(kit): add addRouteMiddleware
method (#18553)
This commit is contained in:
parent
a6a2978978
commit
76a08e3ccd
@ -62,6 +62,7 @@ description: Nuxt Kit provides composable utilities to help interacting with Nux
|
||||
|
||||
- `extendPages (callback: pages => void)`
|
||||
- `extendRouteRules (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions)`
|
||||
- `addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions)`
|
||||
|
||||
### Plugins
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
import type { NuxtHooks } from '@nuxt/schema'
|
||||
import type { NuxtHooks, NuxtMiddleware } from '@nuxt/schema'
|
||||
import type { NitroRouteConfig } from 'nitropack'
|
||||
import { defu } from 'defu'
|
||||
import { useNuxt } from './context'
|
||||
@ -34,3 +34,31 @@ export function extendRouteRules (route: string, rule: NitroRouteConfig, options
|
||||
: defu(opts.routeRules[route], rule)
|
||||
}
|
||||
}
|
||||
|
||||
export interface AddRouteMiddlewareOptions {
|
||||
/**
|
||||
* Override existing middleware with the same name, if it exists
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
override?: boolean
|
||||
}
|
||||
|
||||
export function addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions = {}) {
|
||||
const nuxt = useNuxt()
|
||||
const middlewares = Array.isArray(input) ? input : [input]
|
||||
nuxt.hook('app:resolve', (app) => {
|
||||
for (const middleware of middlewares) {
|
||||
const find = app.middleware.findIndex(item => item.name === middleware.name)
|
||||
if (find >= 0) {
|
||||
if (options.override === true) {
|
||||
app.middleware[find] = middleware
|
||||
} else {
|
||||
console.warn(`'${middleware.name}' middleware already exists at '${app.middleware[find].path}'. You can set \`override: true\` to replace it.`)
|
||||
}
|
||||
} else {
|
||||
app.middleware.push(middleware)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user