-
-
Notifications
You must be signed in to change notification settings - Fork 464
/
middleware.ts
62 lines (54 loc) · 1.52 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import type { Context } from '../../context'
import type { Env, MiddlewareHandler } from '../../types'
export const SSG_CONTEXT = 'HONO_SSG_CONTEXT'
export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })
interface SSGParam {
[key: string]: string
}
export type SSGParams = SSGParam[]
interface SSGParamsMiddleware {
<E extends Env = Env>(
generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>
): MiddlewareHandler<E>
<E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>
}
export type AddedSSGDataRequest = Request & {
ssgParams?: SSGParams
}
/**
* Define SSG Route
*/
export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {
;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)
await next()
}
/**
* @experimental
* `isSSGContext` is an experimental feature.
* The API might be changed.
*/
export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]
/**
* @experimental
* `disableSSG` is an experimental feature.
* The API might be changed.
*/
export const disableSSG = (): MiddlewareHandler =>
async function disableSSG(c, next) {
if (isSSGContext(c)) {
return SSG_DISABLED_RESPONSE
}
await next()
}
/**
* @experimental
* `onlySSG` is an experimental feature.
* The API might be changed.
*/
export const onlySSG = (): MiddlewareHandler =>
async function onlySSG(c, next) {
if (!isSSGContext(c)) {
return c.notFound()
}
await next()
}