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
Provenance
- Commit
3fecc04- Tree
26905fd- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
06fcf68
3 files changed+60 added−22 removed
modified:deno_dist/helper/ssg/index.ts+19 added-11 removed
4 unmodified lines5 import { bufferToString } from '../../utils/buffer.ts'6 import { getExtension } from '../../utils/mime.ts'7 import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils.ts'8 9-export const X_HONO_SSG_HEADER_KEY = 'x-hono-ssg'10-export const X_HONO_DISABLE_SSG_HEADER_KEY = 'x-hono-disable-ssg'9+const SSG_CONTEXT = 'HONO_SSG_CONTEXT'10+export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })11 12 /**13 * @experimental14 * `FileSystemModule` is an experimental feature.110 unmodified lines125 // GET Route Info126 const thisRouteBaseURL = new URL(route.path, baseURL).toString()127 128 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 continue14 unmodified lines147 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 lines260 }261 262 /**263 * @experimental263- * `disableSSG` is an experimental feature.264+ * `isSSGContext` is an experimental feature.265 * The API might be changed.266 */267+export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]268 269+/**270+ * @experimental271+ * `disableSSG` is an experimental feature.272+ * The API might be changed.273+ */274 export 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 }281 282 /**283 * @experimental1 unmodified line285 * The API might be changed.286 */287 export 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 lines3 // eslint-disable-next-line @typescript-eslint/no-unused-vars4 import { jsx } from '../../jsx'5 import { poweredBy } from '../../middleware/powered-by'6 import {7+ SSG_DISABLED_RESPONSE,8 fetchRoutesContent,9 saveContentToFiles,10 ssgParams,11 toSSG,12+ isSSGContext,13 disableSSG,14 onlySSG,15 } from './index'16 import type {337 unmodified lines354 expect(htmlMap.has('/foo:bar')).toBeTruthy()355 })356 })357 358+describe('isSSGContext()', () => {359+ const app = new Hono()360+ app.get('/', (c) => c.html(<h1>{isSSGContext(c) ? 'SSG' : 'noSSG'}</h1>))361+362+ 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+ })369+370+ 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+})375+376 describe('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>))382 383 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 })390 391 it('Should return 404 response if onlySSG() is set', async () => {392 const res = await app.request('/static-page')3 unmodified linesmodified:src/helper/ssg/index.ts+19 added-11 removed
4 unmodified lines5 import { bufferToString } from '../../utils/buffer'6 import { getExtension } from '../../utils/mime'7 import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'8 9-export const X_HONO_SSG_HEADER_KEY = 'x-hono-ssg'10-export const X_HONO_DISABLE_SSG_HEADER_KEY = 'x-hono-disable-ssg'9+const SSG_CONTEXT = 'HONO_SSG_CONTEXT'10+export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })11 12 /**13 * @experimental14 * `FileSystemModule` is an experimental feature.110 unmodified lines125 // GET Route Info126 const thisRouteBaseURL = new URL(route.path, baseURL).toString()127 128 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 continue14 unmodified lines147 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 lines260 }261 262 /**263 * @experimental263- * `disableSSG` is an experimental feature.264+ * `isSSGContext` is an experimental feature.265 * The API might be changed.266 */267+export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]268 269+/**270+ * @experimental271+ * `disableSSG` is an experimental feature.272+ * The API might be changed.273+ */274 export 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 }281 282 /**283 * @experimental1 unmodified line285 * The API might be changed.286 */287 export 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 }