feat(kit): add prepend option to addRouteMiddleware (#28496)

This commit is contained in:
Son Tran 2024-08-13 01:41:01 +07:00 committed by GitHub
parent 2c3518e312
commit c4cad445ea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 24 additions and 2 deletions

View File

@ -209,6 +209,7 @@ type NuxtMiddleware = {
interface AddRouteMiddlewareOptions {
override?: boolean
prepend?: boolean
}
```
@ -246,7 +247,21 @@ A middleware object or an array of middleware objects with the following propert
**Default**: `{}`
Options to pass to the middleware. If `override` is set to `true`, it will override the existing middleware with the same name.
- `override` (optional)
**Type**: `boolean`
**Default**: `false`
If enabled, overrides the existing middleware with the same name.
- `prepend` (optional)
**Type**: `boolean`
**Default**: `false`
If enabled, prepends the middleware to the list of existing middleware.
### Examples
@ -272,7 +287,7 @@ export default defineNuxtModule({
name: 'auth',
path: resolver.resolve('runtime/auth.ts'),
global: true
})
}, { prepend: true })
}
})
```

View File

@ -35,6 +35,11 @@ export interface AddRouteMiddlewareOptions {
* @default false
*/
override?: boolean
/**
* Prepend middleware to the list
* @default false
*/
prepend?: boolean
}
export function addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions = {}) {
@ -51,6 +56,8 @@ export function addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], op
} else {
logger.warn(`'${middleware.name}' middleware already exists at '${foundPath}'. You can set \`override: true\` to replace it.`)
}
} else if (options.prepend === true) {
app.middleware.unshift({ ...middleware })
} else {
app.middleware.push({ ...middleware })
}