Skip to content

Commit 340d484

Browse files
authored
Merge branch 'main' into repo-sync
2 parents 3476b6f + 0c0e0da commit 340d484

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

middleware/render-page.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import Page from '../lib/page.js'
55
import { isConnectionDropped } from './halt-on-dropped-connection.js'
66
import { nextApp, nextHandleRequest } from './next.js'
77

8+
const pageCache = new Map()
9+
810
export default async function renderPage(req, res, next) {
911
if (req.path.startsWith('/storybook')) {
1012
return nextHandleRequest(req, res)
@@ -29,6 +31,45 @@ export default async function renderPage(req, res, next) {
2931
// Is the request for JSON debugging info?
3032
const isRequestingJsonForDebugging = 'json' in req.query && process.env.NODE_ENV !== 'production'
3133

34+
// ****** temporary caching measure for holiday spam prevention *********
35+
36+
const isApiPage =
37+
req.context.currentPathWithoutLanguage.includes('rest/reference') ||
38+
req.context.currentPathWithoutLanguage.includes('graphql/reference')
39+
40+
// Serve from the cache if possible
41+
const isCacheable =
42+
// Skip for CI
43+
!process.env.CI &&
44+
// Skip for tests
45+
process.env.NODE_ENV !== 'test' &&
46+
// Skip for HTTP methods other than GET
47+
req.method === 'GET' &&
48+
// Skip for JSON debugging info requests
49+
!isRequestingJsonForDebugging &&
50+
// Only API pages
51+
isApiPage
52+
53+
// don't cache query strings
54+
const originalUrl = req.originalUrl.split('?')[0]
55+
56+
if (isCacheable) {
57+
// Stop processing if the connection was already dropped
58+
if (isConnectionDropped(req, res)) return
59+
60+
const cachedHtml = pageCache.get(originalUrl)
61+
if (cachedHtml) {
62+
// Stop processing if the connection was already dropped
63+
if (isConnectionDropped(req, res)) return
64+
65+
console.log(`Serving from cached version of ${originalUrl}`)
66+
// statsd.increment('page.sent_from_cache')
67+
return res.send(cachedHtml)
68+
}
69+
}
70+
71+
// ****** [end] temporary caching measure for holiday spam prevention *********
72+
3273
// add page context
3374
const context = Object.assign({}, req.context, { page })
3475

@@ -104,5 +145,12 @@ export default async function renderPage(req, res, next) {
104145
// Hand rendering over to NextJS
105146
req.context.renderedPage = context.renderedPage
106147
req.context.miniTocItems = context.miniTocItems
148+
149+
// ****** temporary caching measure for holiday spam prevention *********
150+
if (isCacheable) {
151+
pageCache.set(originalUrl, req.context.renderedPage)
152+
}
153+
// ****** [end] temporary caching measure for holiday spam prevention *********
154+
107155
return nextHandleRequest(req, res)
108156
}

0 commit comments

Comments
 (0)