2023-02-06 23:24:56 +00:00
|
|
|
import type { NuxtHooks, NuxtMiddleware } from '@nuxt/schema'
|
2023-01-21 16:54:02 +00:00
|
|
|
import type { NitroRouteConfig } from 'nitropack'
|
|
|
|
import { defu } from 'defu'
|
2021-11-21 16:14:46 +00:00
|
|
|
import { useNuxt } from './context'
|
2023-09-19 21:26:15 +00:00
|
|
|
import { logger } from './logger'
|
2023-12-23 14:22:58 +00:00
|
|
|
import { toArray } from './utils'
|
2021-11-21 16:14:46 +00:00
|
|
|
|
|
|
|
export function extendPages (cb: NuxtHooks['pages:extend']) {
|
2024-06-19 12:56:54 +00:00
|
|
|
useNuxt().hook('pages:extend', cb)
|
2021-11-21 16:14:46 +00:00
|
|
|
}
|
2023-01-21 16:54:02 +00:00
|
|
|
|
|
|
|
export interface ExtendRouteRulesOptions {
|
|
|
|
/**
|
|
|
|
* Override route rule config
|
|
|
|
* @default false
|
|
|
|
*/
|
|
|
|
override?: boolean
|
|
|
|
}
|
|
|
|
|
|
|
|
export function extendRouteRules (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions = {}) {
|
|
|
|
const nuxt = useNuxt()
|
|
|
|
for (const opts of [nuxt.options, nuxt.options.nitro]) {
|
|
|
|
if (!opts.routeRules) {
|
|
|
|
opts.routeRules = {}
|
|
|
|
}
|
|
|
|
opts.routeRules[route] = options.override
|
|
|
|
? defu(rule, opts.routeRules[route])
|
|
|
|
: defu(opts.routeRules[route], rule)
|
|
|
|
}
|
|
|
|
}
|
2023-02-06 23:24:56 +00:00
|
|
|
|
|
|
|
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()
|
2023-12-23 14:22:58 +00:00
|
|
|
const middlewares = toArray(input)
|
2023-02-06 23:24:56 +00:00
|
|
|
nuxt.hook('app:resolve', (app) => {
|
|
|
|
for (const middleware of middlewares) {
|
|
|
|
const find = app.middleware.findIndex(item => item.name === middleware.name)
|
|
|
|
if (find >= 0) {
|
2024-06-13 21:52:57 +00:00
|
|
|
const foundPath = app.middleware[find].path
|
|
|
|
if (foundPath === middleware.path) { continue }
|
2023-02-06 23:24:56 +00:00
|
|
|
if (options.override === true) {
|
2024-03-15 22:38:07 +00:00
|
|
|
app.middleware[find] = { ...middleware }
|
2023-02-06 23:24:56 +00:00
|
|
|
} else {
|
2024-06-13 21:52:57 +00:00
|
|
|
logger.warn(`'${middleware.name}' middleware already exists at '${foundPath}'. You can set \`override: true\` to replace it.`)
|
2023-02-06 23:24:56 +00:00
|
|
|
}
|
|
|
|
} else {
|
2024-03-15 22:38:07 +00:00
|
|
|
app.middleware.push({ ...middleware })
|
2023-02-06 23:24:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|