* fast HEAD requests

* update test
This commit is contained in:
Peter Bengtsson 2022-05-13 10:46:57 -04:00 коммит произвёл GitHub
Родитель 39f7284fad
Коммит 8580fb5e42
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
3 изменённых файлов: 27 добавлений и 1 удалений

16
middleware/fast-head.js Normal file
Просмотреть файл

@ -0,0 +1,16 @@
import { cacheControlFactory } from './cache-control.js'
const cacheControl = cacheControlFactory(60 * 60 * 24)
export default function fastHead(req, res, next) {
const { context } = req
const { page } = context
if (page) {
// Since the *presence* is not affected by the request, we can cache
// this and allow the CDN to hold on to it.
cacheControl(res)
return res.status(200).send('')
}
next()
}

Просмотреть файл

@ -65,6 +65,7 @@ import archivedAssetRedirects from './archived-asset-redirects.js'
import favicons from './favicons.js'
import setStaticAssetCaching from './static-asset-caching.js'
import protect from './overload-protection.js'
import fastHead from './fast-head.js'
const { DEPLOYMENT_ENV, NODE_ENV } = process.env
const isDevelopment = NODE_ENV === 'development'
@ -309,6 +310,10 @@ export default function (app) {
// Check for a dropped connection before proceeding (again)
app.use(haltOnDroppedConnection)
// Specifically deal with HEAD requests before doing the slower
// full page rendering.
app.head('/*', fastHead)
// *** Preparation for render-page: contextualizers ***
app.use(asyncMiddleware(instrument(releaseNotes, './contextualizers/release-notes')))
app.use(instrument(graphQL, './contextualizers/graphql'))

Просмотреть файл

@ -29,8 +29,13 @@ describe('server', () => {
test('supports HEAD requests', async () => {
const res = await head('/en')
expect(res.statusCode).toBe(200)
expect(res.headers).not.toHaveProperty('content-length')
expect(res.headers['content-length']).toBe('0')
expect(res.text).toBe('')
// Because the HEAD requests can't be different no matter what's
// in the request headers (Accept-Language or Cookies)
// it's safe to let it cache. The only key is the URL.
expect(res.headers['cache-control']).toContain('public')
expect(res.headers['cache-control']).toMatch(/max-age=\d+/)
})
test('renders the homepage', async () => {