Skip to content
Myr

refactor(ssg): check `c.env` variables to disable/enable SSG (#2179)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* refactor(ssg): generate static files only for GET or ALL routes * feat(ssg): Introduce `isSSGContext()` * refactor(ssg): use environment variable and special response object to disable/enable SSG * chore: denoify * refactor(ssg): tweaks check for SSG_DISABLED_RESPONSE

authored by Taku Amano · committed by GitHub · parent 06fcf68 · Browse files · 3 files+60 added−22 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+60 added−22 removed

  • tests:+22 added−0 removed
  • other:+38 added−22 removed

3 files+60 added−22 removed

modified:deno_dist/helper/ssg/index.ts+19 added-11 removed
4 unmodified lines
5import { bufferToString } from '../../utils/buffer.ts'6import { getExtension } from '../../utils/mime.ts'7import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils.ts'89export const X_HONO_SSG_HEADER_KEY = 'x-hono-ssg'10export const X_HONO_DISABLE_SSG_HEADER_KEY = 'x-hono-disable-ssg'9const SSG_CONTEXT = 'HONO_SSG_CONTEXT'10export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })1112/**13 * @experimental14 * `FileSystemModule` is an experimental feature.
110 unmodified lines
125 // GET Route Info126 const thisRouteBaseURL = new URL(route.path, baseURL).toString()127128 let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest129 forGetInfoURLRequest.headers.set(X_HONO_SSG_HEADER_KEY, 'true')129 if (beforeRequestHook) {130 const maybeRequest = beforeRequestHook(forGetInfoURLRequest)131 if (!maybeRequest) {132 continue
14 unmodified lines
147 headers: forGetInfoURLRequest.headers,148 }149 for (const param of forGetInfoURLRequest.ssgParams) {150 const replacedUrlParam = replaceUrlParam(route.path, param)152 let response = await app.request(replacedUrlParam, requestInit)153 if (response.headers.get(X_HONO_DISABLE_SSG_HEADER_KEY)) {151 let response = await app.request(replacedUrlParam, requestInit, {152 [SSG_CONTEXT]: true,153 })154 if (response === SSG_DISABLED_RESPONSE) {155 continue156 }157 if (afterResponseHook) {158 const maybeResponse = afterResponseHook(response)
101 unmodified lines
260}261262/**263 * @experimental263 * `disableSSG` is an experimental feature.264 * `isSSGContext` is an experimental feature.265 * The API might be changed.266 */267export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]268269/**270 * @experimental271 * `disableSSG` is an experimental feature.272 * The API might be changed.273 */274export const disableSSG = (): MiddlewareHandler =>275 async function disableSSG(c, next) {276 if (isSSGContext(c)) {277 return SSG_DISABLED_RESPONSE278 }279 await next()270 c.header(X_HONO_DISABLE_SSG_HEADER_KEY, 'true')280 }281282/**283 * @experimental
1 unmodified line
285 * The API might be changed.286 */287export const onlySSG = (): MiddlewareHandler =>288 async function onlySSG(c, next) {280 const headerValue = c.req.raw.headers.get(X_HONO_SSG_HEADER_KEY)281 if (headerValue) {282 await next()289 if (!isSSGContext(c)) {290 return c.notFound()291 }284 return c.notFound()292 await next()293 }
modified:src/helper/ssg/index.test.tsx+22 added
2 unmodified lines
3// eslint-disable-next-line @typescript-eslint/no-unused-vars4import { jsx } from '../../jsx'5import { poweredBy } from '../../middleware/powered-by'6import {7 SSG_DISABLED_RESPONSE,8 fetchRoutesContent,9 saveContentToFiles,10 ssgParams,11 toSSG,12 isSSGContext,13 disableSSG,14 onlySSG,15} from './index'16import type {
337 unmodified lines
354 expect(htmlMap.has('/foo:bar')).toBeTruthy()355 })356})357358describe('isSSGContext()', () => {359 const app = new Hono()360 app.get('/', (c) => c.html(<h1>{isSSGContext(c) ? 'SSG' : 'noSSG'}</h1>))361362 it('Should not generate the page if disableSSG is set', async () => {363 const htmlMap = await fetchRoutesContent(app)364 expect(await htmlMap.get('/')).toEqual({365 content: '<h1>SSG</h1>',366 mimeType: 'text/html',367 })368 })369370 it('Should return 404 response if onlySSG() is set', async () => {371 const res = await app.request('/')372 expect(await res.text()).toBe('<h1>noSSG</h1>')373 })374})375376describe('disableSSG/onlySSG middlewares', () => {377 const app = new Hono()378 app.get('/', (c) => c.html(<h1>Hello</h1>))379 app.get('/api', disableSSG(), (c) => c.text('an-api'))380 app.get('/disable-by-response', () => SSG_DISABLED_RESPONSE)381 app.get('/static-page', onlySSG(), (c) => c.html(<h1>Welcome to my site</h1>))382383 it('Should not generate the page if disableSSG is set', async () => {384 const htmlMap = await fetchRoutesContent(app)385 expect(htmlMap.has('/')).toBe(true)386 expect(htmlMap.has('/static-page')).toBe(true)387 expect(htmlMap.has('/api')).toBe(false)388 expect(htmlMap.has('/disable-by-response')).toBe(false)389 })390391 it('Should return 404 response if onlySSG() is set', async () => {392 const res = await app.request('/static-page')
3 unmodified lines
modified:src/helper/ssg/index.ts+19 added-11 removed
4 unmodified lines
5import { bufferToString } from '../../utils/buffer'6import { getExtension } from '../../utils/mime'7import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'89export const X_HONO_SSG_HEADER_KEY = 'x-hono-ssg'10export const X_HONO_DISABLE_SSG_HEADER_KEY = 'x-hono-disable-ssg'9const SSG_CONTEXT = 'HONO_SSG_CONTEXT'10export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })1112/**13 * @experimental14 * `FileSystemModule` is an experimental feature.
110 unmodified lines
125 // GET Route Info126 const thisRouteBaseURL = new URL(route.path, baseURL).toString()127128 let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest129 forGetInfoURLRequest.headers.set(X_HONO_SSG_HEADER_KEY, 'true')129 if (beforeRequestHook) {130 const maybeRequest = beforeRequestHook(forGetInfoURLRequest)131 if (!maybeRequest) {132 continue
14 unmodified lines
147 headers: forGetInfoURLRequest.headers,148 }149 for (const param of forGetInfoURLRequest.ssgParams) {150 const replacedUrlParam = replaceUrlParam(route.path, param)152 let response = await app.request(replacedUrlParam, requestInit)153 if (response.headers.get(X_HONO_DISABLE_SSG_HEADER_KEY)) {151 let response = await app.request(replacedUrlParam, requestInit, {152 [SSG_CONTEXT]: true,153 })154 if (response === SSG_DISABLED_RESPONSE) {155 continue156 }157 if (afterResponseHook) {158 const maybeResponse = afterResponseHook(response)
101 unmodified lines
260}261262/**263 * @experimental263 * `disableSSG` is an experimental feature.264 * `isSSGContext` is an experimental feature.265 * The API might be changed.266 */267export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]268269/**270 * @experimental271 * `disableSSG` is an experimental feature.272 * The API might be changed.273 */274export const disableSSG = (): MiddlewareHandler =>275 async function disableSSG(c, next) {276 if (isSSGContext(c)) {277 return SSG_DISABLED_RESPONSE278 }279 await next()270 c.header(X_HONO_DISABLE_SSG_HEADER_KEY, 'true')280 }281282/**283 * @experimental
1 unmodified line
285 * The API might be changed.286 */287export const onlySSG = (): MiddlewareHandler =>288 async function onlySSG(c, next) {280 const headerValue = c.req.raw.headers.get(X_HONO_SSG_HEADER_KEY)281 if (headerValue) {282 await next()289 if (!isSSGContext(c)) {290 return c.notFound()291 }284 return c.notFound()292 await next()293 }