Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor!: rename routeOptions to routeRules #593

Merged
merged 4 commits into from
Oct 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/content/1.guide/1.introduction/5.cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const myFn = cachedFunction(async () => {
import { defineNitroConfig } from 'nitropack'

export default defineNitroConfig({
routes: {
routeRules: {
'/blog/**': { swr: true }
}
})
Expand Down
4 changes: 2 additions & 2 deletions docs/content/3.config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ export default <NitroErrorHandler> function (error, event) {
}
```

## `routes`
## `routeRules`

**πŸ§ͺ Experimental!**

Expand All @@ -181,7 +181,7 @@ When `cache` option is set, handlers matching pattern will be automatically wrap

```js
{
routes: {
routeRules: {
'/blog/**': { swr: true },
'/blog/**': { swr: 600 },
'/blog/**': { static: true },
Expand Down
2 changes: 1 addition & 1 deletion src/imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const nitroImports: Preset[] = [
'defineNitroPlugin',
'nitroPlugin',
'defineRenderHandler',
'getRouteOptions'
'getRouteRules'
]
}
]
39 changes: 21 additions & 18 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { withLeadingSlash, withoutTrailingSlash, withTrailingSlash } from 'ufo'
import { isTest, isDebug } from 'std-env'
import { findWorkspaceDir } from 'pkg-types'
import { resolvePath, detectTarget } from './utils'
import type { NitroConfig, NitroOptions, NitroRouteConfig, NitroRouteOptions } from './types'
import type { NitroConfig, NitroOptions, NitroRouteConfig, NitroRouteRules } from './types'
import { runtimeDir, pkgDir } from './dirs'
import * as _PRESETS from './presets'
import { nitroImports } from './imports'
Expand Down Expand Up @@ -54,7 +54,7 @@ const NitroDefaults: NitroConfig = {
handlers: [],
devHandlers: [],
errorHandler: '#internal/nitro/error',
routes: {},
routeRules: {},
prerender: {
crawlLinks: false,
ignore: [],
Expand Down Expand Up @@ -183,56 +183,59 @@ export async function loadOptions (configOverrides: NitroConfig = {}): Promise<N
})
}

// Normalize route rules (NitroRouteConfig => NitroRouteOptions)
const routes: { [p: string]: NitroRouteOptions } = {}
for (const path in options.routes) {
const routeConfig = options.routes[path] as NitroRouteConfig
const routeOptions: NitroRouteOptions = {
// Backward compatibility for options.routes
options.routeRules = defu(options.routeRules, (options as any).routes || {})

// Normalize route rules (NitroRouteConfig => NitroRouteRules)
const normalizedRules: { [p: string]: NitroRouteRules } = {}
for (const path in options.routeRules) {
const routeConfig = options.routeRules[path] as NitroRouteConfig
const routeRules: NitroRouteRules = {
...routeConfig,
redirect: undefined
}
// Redirect
if (routeConfig.redirect) {
routeOptions.redirect = {
routeRules.redirect = {
to: '/',
statusCode: 307,
...(typeof routeConfig.redirect === 'string' ? { to: routeConfig.redirect } : routeConfig.redirect)
}
}
// CORS
if (routeConfig.cors) {
routeOptions.headers = {
routeRules.headers = {
'access-control-allow-origin': '*',
'access-control-allowed-methods': '*',
'access-control-allow-headers': '*',
'access-control-max-age': '0',
...routeOptions.headers
...routeRules.headers
}
}
// Cache: swr
if (routeConfig.swr) {
routeOptions.cache = routeOptions.cache || {}
routeOptions.cache.swr = true
routeRules.cache = routeRules.cache || {}
routeRules.cache.swr = true
if (typeof routeConfig.swr === 'number') {
routeOptions.cache.maxAge = routeConfig.swr
routeRules.cache.maxAge = routeConfig.swr
}
}
// Cache: static
if (routeConfig.static) {
routeOptions.cache = routeOptions.cache || {}
routeOptions.cache.static = true
routeRules.cache = routeRules.cache || {}
routeRules.cache.static = true
}
routes[path] = routeOptions
normalizedRules[path] = routeRules
}
options.routes = routes
options.routeRules = normalizedRules

options.baseURL = withLeadingSlash(withTrailingSlash(options.baseURL))
options.runtimeConfig = defu(options.runtimeConfig, {
app: {
baseURL: options.baseURL
},
nitro: {
routes: options.routes
routeRules: options.routeRules
}
})

Expand Down
16 changes: 8 additions & 8 deletions src/presets/netlify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,17 +82,17 @@ async function writeRedirects (nitro: Nitro) {
let contents = '/* /.netlify/functions/server 200'

// Rewrite static cached paths to builder functions
for (const [key] of Object.entries(nitro.options.routes)
.filter(([_, routeOptions]) => routeOptions.cache?.static || routeOptions.cache?.swr)
for (const [key] of Object.entries(nitro.options.routeRules)
.filter(([_, routeRules]) => routeRules.cache?.static || routeRules.cache?.swr)
) {
contents = `${key.replace('/**', '/*')}\t/.netlify/builders/server 200\n` + contents
}

for (const [key, routeOptions] of Object.entries(nitro.options.routes).filter(([_, routeOptions]) => routeOptions.redirect)) {
for (const [key, routeRules] of Object.entries(nitro.options.routeRules).filter(([_, routeRules]) => routeRules.redirect)) {
// TODO: Remove map when netlify support 307/308
let code = routeOptions.redirect.statusCode
let code = routeRules.redirect.statusCode
code = ({ 307: 302, 308: 301 })[code] || code
contents = `${key.replace('/**', '/*')}\t${routeOptions.redirect.to}\t${code}\n` + contents
contents = `${key.replace('/**', '/*')}\t${routeRules.redirect.to}\t${code}\n` + contents
}

if (existsSync(redirectsPath)) {
Expand All @@ -112,11 +112,11 @@ async function writeHeaders (nitro: Nitro) {
const headersPath = join(nitro.options.output.publicDir, '_headers')
let contents = ''

for (const [path, routeOptions] of Object.entries(nitro.options.routes)
.filter(([_, routeOptions]) => routeOptions.headers)) {
for (const [path, routeRules] of Object.entries(nitro.options.routeRules)
.filter(([_, routeRules]) => routeRules.headers)) {
const headers = [
path.replace('/**', '/*'),
...Object.entries({ ...routeOptions.headers }).map(([header, value]) => ` ${header}: ${value}`)
...Object.entries({ ...routeRules.headers }).map(([header, value]) => ` ${header}: ${value}`)
].join('\n')

contents += headers + '\n'
Expand Down
16 changes: 8 additions & 8 deletions src/presets/vercel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,20 +82,20 @@ function generateBuildConfig (nitro: Nitro) {
)
),
routes: [
...Object.entries(nitro.options.routes)
.filter(([_, routeOptions]) => routeOptions.redirect || routeOptions.headers)
.map(([path, routeOptions]) => {
...Object.entries(nitro.options.routeRules)
.filter(([_, routeRules]) => routeRules.redirect || routeRules.headers)
.map(([path, routeRules]) => {
let route = {
src: path.replace('/**', '/.*')
}
if (routeOptions.redirect) {
if (routeRules.redirect) {
route = defu(route, {
status: routeOptions.redirect.statusCode,
headers: { Location: routeOptions.redirect.to }
status: routeRules.redirect.statusCode,
headers: { Location: routeRules.redirect.to }
})
}
if (routeOptions.headers) {
route = defu(route, { headers: routeOptions.headers })
if (routeRules.headers) {
route = defu(route, { headers: routeRules.headers })
}
return route
}),
Expand Down
10 changes: 5 additions & 5 deletions src/runtime/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { createHooks, Hookable } from 'hookable'
import { useRuntimeConfig } from './config'
import { timingMiddleware } from './timing'
import { cachedEventHandler } from './cache'
import { createRouteOptionsHandler, getRouteOptionsForPath } from './route-options'
import { createRouteRulesHandler, getRouteRulesForPath } from './route-rules'
import { plugins } from '#internal/nitro/virtual/plugins'
import errorHandler from '#internal/nitro/virtual/error-handler'
import { handlers } from '#internal/nitro/virtual/server-handlers'
Expand Down Expand Up @@ -34,17 +34,17 @@ function createNitroApp (): NitroApp {

const router = createRouter()

h3App.use(createRouteOptionsHandler())
h3App.use(createRouteRulesHandler())

for (const h of handlers) {
let handler = h.lazy ? lazyEventHandler(h.handler) : h.handler

// Wrap matching handlers for caching route options
const routeOptions = getRouteOptionsForPath(h.route.replace(/:\w+|\*\*/g, '_'))
if (routeOptions.cache) {
const routeRules = getRouteRulesForPath(h.route.replace(/:\w+|\*\*/g, '_'))
if (routeRules.cache) {
handler = cachedEventHandler(handler, {
group: 'nitro/routes',
...routeOptions.cache
...routeRules.cache
})
}

Expand Down
14 changes: 5 additions & 9 deletions src/runtime/entries/netlify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,18 @@ import '#internal/nitro/virtual/polyfill'
import type { Handler, HandlerResponse, HandlerContext, HandlerEvent } from '@netlify/functions/dist/main'
import type { APIGatewayProxyEventHeaders } from 'aws-lambda'
import { withQuery } from 'ufo'
import { createRouter as createMatcher } from 'radix3'
import { nitroApp } from '../app'
import { useRuntimeConfig } from '../config'
import { getRouteRulesForPath } from '../route-rules'

export const handler: Handler = async function handler (event, context) {
const config = useRuntimeConfig()
const routerOptions = createMatcher({ routes: config.nitro.routes })

const query = { ...event.queryStringParameters, ...event.multiValueQueryStringParameters }
const url = withQuery(event.path, query)
const routeOptions = routerOptions.lookup(url) || {}
const routeRules = getRouteRulesForPath(url)

if (routeOptions.static || routeOptions.swr) {
if (routeRules.cache && (routeRules.cache.swr || routeRules.cache.static)) {
const builder = await import('@netlify/functions').then(r => r.builder || r.default.builder)
const ttl = typeof routeOptions.swr === 'number' ? routeOptions.swr : 60
const swrHandler = routeOptions.swr
const ttl = typeof routeRules.cache.swr === 'number' ? routeRules.cache.swr : 60
const swrHandler = routeRules.cache.swr
? ((event, context) => lambda(event, context).then(r => ({ ...r, ttl }))) as Handler
: lambda
return builder(swrHandler)(event, context) as any
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ export * from './cache'
export { useNitroApp } from './app'
export * from './plugin'
export * from './renderer'
export { getRouteOptions } from './route-options'
export { getRouteRules } from './route-rules'
36 changes: 0 additions & 36 deletions src/runtime/route-options.ts

This file was deleted.

36 changes: 36 additions & 0 deletions src/runtime/route-rules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { eventHandler, H3Event, sendRedirect, setHeaders } from 'h3'
import defu from 'defu'
import { createRouter as createRadixRouter, toRouteMatcher } from 'radix3'
import { useRuntimeConfig } from './config'
import type { NitroRouteRules } from 'nitropack'

const config = useRuntimeConfig()
const _routeRulesMatcher = toRouteMatcher(createRadixRouter({ routes: config.nitro.routeRules }))

export function createRouteRulesHandler () {
return eventHandler((event) => {
// Match route options against path
const routeRules = getRouteRules(event)
// Apply headers options
if (routeRules.headers) {
setHeaders(event, routeRules.headers)
}
// Apply redirect options
if (routeRules.redirect) {
return sendRedirect(event, routeRules.redirect.to, routeRules.redirect.statusCode)
}
})
}

export function getRouteRules (event: H3Event): NitroRouteRules {
event.context._nitro = event.context._nitro || {}
if (!event.context._nitro.routeRules) {
const path = new URL(event.req.url, 'http://localhost').pathname
event.context._nitro.routeRules = getRouteRulesForPath(path)
}
return event.context._nitro.routeRules
}

export function getRouteRulesForPath (path: string): NitroRouteRules {
return defu({}, ..._routeRulesMatcher.matchAll(path).reverse())
}
8 changes: 4 additions & 4 deletions src/types/nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ type DeepPartial<T> = T extends Record<string, any> ? { [P in keyof T]?: DeepPar

export type NitroPreset = NitroConfig | (() => NitroConfig)

export interface NitroConfig extends DeepPartial<Omit<NitroOptions, 'routes'>> {
export interface NitroConfig extends DeepPartial<Omit<NitroOptions, 'routeRules'>> {
extends?: string | string[] | NitroPreset
routes?: { [path: string]: NitroRouteConfig }
routeRules?: { [path: string]: NitroRouteConfig }
}

export interface PublicAssetDir {
Expand Down Expand Up @@ -104,7 +104,7 @@ export interface NitroRouteConfig {
static?: boolean | number
}

export interface NitroRouteOptions extends Omit<NitroRouteConfig, 'redirect' | 'cors' | 'swr' | 'static'> {
export interface NitroRouteRules extends Omit<NitroRouteConfig, 'redirect' | 'cors' | 'swr' | 'static'> {
redirect?: { to: string, statusCode: HTTPStatusCode }
}

Expand Down Expand Up @@ -165,7 +165,7 @@ export interface NitroOptions extends PresetOptions {
// Routing
baseURL: string,
handlers: NitroEventHandler[]
routes: { [path: string]: NitroRouteOptions }
routeRules: { [path: string]: NitroRouteRules }
devHandlers: NitroDevEventHandler[]
errorHandler: string
devErrorHandler: NitroErrorHandler
Expand Down
2 changes: 1 addition & 1 deletion test/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export async function setupTest (preset) {
rootDir: ctx.rootDir,
serveStatic: preset !== 'cloudflare' && preset !== 'vercel-edge',
output: { dir: ctx.outDir },
routes: {
routeRules: {
'/rules/headers': { headers: { 'cache-control': 's-maxage=60' } },
'/rules/cors': { cors: true, headers: { 'access-control-allowed-methods': 'GET' } },
'/rules/redirect': { redirect: '/base' },
Expand Down