Fix TechDocs backend cache bug on HEAD request.

Signed-off-by: Eric Peterson <ericpeterson@spotify.com>
This commit is contained in:
Eric Peterson
2022-03-18 11:23:50 +01:00
parent e47370f9e6
commit 7762d54200
3 changed files with 29 additions and 1 deletions
@@ -0,0 +1,5 @@
---
'@backstage/plugin-techdocs-backend': patch
---
Fixed a bug affecting those with cache enabled that would result in empty content being cached if the first attempt to load a static asset from storage were made via a `HEAD` request, rather than a `GET` request.
@@ -85,6 +85,15 @@ describe('createCacheMiddleware', () => {
expect(cache.set).not.toHaveBeenCalled();
});
it('checks cache for head requests', async () => {
cache.get.mockResolvedValueOnce(getMockHttpResponseFor('xyz'));
await request(app).head('/static/docs/foo.html').expect(200);
await waitForSocketClose();
expect(cache.set).not.toHaveBeenCalled();
});
it('sets cache when content is cacheable', async () => {
const expectedPath = 'default/api/xyz/index.html';
await request(app)
@@ -105,5 +114,13 @@ describe('createCacheMiddleware', () => {
await waitForSocketClose();
expect(cache.set).not.toHaveBeenCalled();
});
it('does not set cache on head requests', async () => {
const expectedPath = 'default/api/xyz/index.html';
await request(app).head(`/static/docs/${expectedPath}`).expect(200);
await waitForSocketClose();
expect(cache.set).not.toHaveBeenCalled();
});
});
});
+7 -1
View File
@@ -36,6 +36,7 @@ export const createCacheMiddleware = ({
cacheMiddleware.use(async (req, res, next) => {
const socket = res.socket;
const isCacheable = req.path.startsWith('/static/docs/');
const isGetRequest = req.method === 'GET';
// Continue early if this is non-cacheable, or there's no socket.
if (!isCacheable || !socket) {
@@ -69,7 +70,12 @@ export const createCacheMiddleware = ({
socket.on('close', async hadError => {
const content = Buffer.concat(chunks);
const head = content.toString('utf8', 0, 12);
if (writeToCache && !hadError && head.match(/HTTP\/\d\.\d 200/)) {
if (
isGetRequest &&
writeToCache &&
!hadError &&
head.match(/HTTP\/\d\.\d 200/)
) {
await cache.set(reqPath, content);
}
});