Skip to content
Myr

middleware.ts

This file

Path

src/helper/ssg/middleware.ts

83 lines · 2.1 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–83why, one step back
1import type { Context } from '../../context'
2import type { Env, MiddlewareHandler } from '../../types'3import { isDynamicRoute } from './utils'45export const SSG_CONTEXT = 'HONO_SSG_CONTEXT'6export const X_HONO_DISABLE_SSG_HEADER_KEY = 'x-hono-disable-ssg'78/**9 * @deprecated10 * Use `X_HONO_DISABLE_SSG_HEADER_KEY` instead.11 * This constant will be removed in the next minor version.12 */13export const SSG_DISABLED_RESPONSE = (() => {14 try {15 return new Response('SSG is disabled', {16 status: 404,17 headers: { [X_HONO_DISABLE_SSG_HEADER_KEY]: 'true' },18 })19 } catch {20 return null21 }22})() as Response2324interface SSGParam {25 [key: string]: string26}27export type SSGParams = SSGParam[]2829interface SSGParamsMiddleware {30 <E extends Env = Env>(31 generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>32 ): MiddlewareHandler<E>33 <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>34}3536export type AddedSSGDataRequest = Request & {37 ssgParams?: SSGParams38}3940/**41 * Define SSG Route42 */43export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {44 if (isDynamicRoute(c.req.path)) {45 ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)46 return c.notFound() // Prevent subsequent handler execution after ssgParams47 }48 await next()49}5051/**52 * @experimental53 * `isSSGContext` is an experimental feature.54 * The API might be changed.55 */56export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]5758/**59 * @experimental60 * `disableSSG` is an experimental feature.61 * The API might be changed.62 */63export const disableSSG = (): MiddlewareHandler =>64 async function disableSSG(c, next) {65 if (isSSGContext(c)) {66 c.header(X_HONO_DISABLE_SSG_HEADER_KEY, 'true')67 return c.notFound()68 }69 await next()70 }7172/**73 * @experimental74 * `onlySSG` is an experimental feature.75 * The API might be changed.76 */77export const onlySSG = (): MiddlewareHandler =>78 async function onlySSG(c, next) {79 if (!isSSGContext(c)) {80 return c.notFound()81 }82 await next()83 }