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 Daniel Roe
parent 4ac3aa1a04
commit 9de596d802
No known key found for this signature in database
GPG Key ID: CBC814C393D93268
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

@ -42,6 +42,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 = {}) {
@ -58,6 +63,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 })
}