feat(kit): add `addRouteMiddleware` method (#18553)

This commit is contained in:
Mehdi HosseinZade 2023-02-07 02:54:56 +03:30 committed by GitHub
parent a6a2978978
commit 76a08e3ccd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 1 deletions

View File

@ -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

View File

@ -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)
}
}
})
}