From 585e8be2e0f7415119b016f5857fab565c8ee06b Mon Sep 17 00:00:00 2001 From: Mehdi HosseinZade Date: Sat, 21 Jan 2023 20:24:02 +0330 Subject: [PATCH] feat(kit): add `extendRouteRules` method (#9771) --- docs/content/1.docs/3.api/4.advanced/2.kit.md | 1 + packages/kit/src/pages.ts | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/docs/content/1.docs/3.api/4.advanced/2.kit.md b/docs/content/1.docs/3.api/4.advanced/2.kit.md index c96798248f..bd90611880 100644 --- a/docs/content/1.docs/3.api/4.advanced/2.kit.md +++ b/docs/content/1.docs/3.api/4.advanced/2.kit.md @@ -61,6 +61,7 @@ description: Nuxt Kit provides composable utilities to help interacting with Nux [source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/pages.ts) - `extendPages (callback: pages => void)` +- `extendRouteRules (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions)` ### Plugins diff --git a/packages/kit/src/pages.ts b/packages/kit/src/pages.ts index 53dbae88dc..1bf33f4ef9 100644 --- a/packages/kit/src/pages.ts +++ b/packages/kit/src/pages.ts @@ -1,4 +1,6 @@ import type { NuxtHooks } from '@nuxt/schema' +import type { NitroRouteConfig } from 'nitropack' +import { defu } from 'defu' import { useNuxt } from './context' import { isNuxt2 } from './compatibility' @@ -11,3 +13,24 @@ export function extendPages (cb: NuxtHooks['pages:extend']) { nuxt.hook('pages:extend', cb) } } + +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) + } +}