From 1b95c4c79470601f4ae0ce19a84129b29a832701 Mon Sep 17 00:00:00 2001 From: Liran Nuna Date: Mon, 22 Oct 2018 11:41:29 -0700 Subject: [PATCH] Handle Etag and If-none-match headers and 304 responses --- server.js | 18 ++++++++++++++---- test/test.js | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/server.js b/server.js index da9ba1f..bcaa291 100644 --- a/server.js +++ b/server.js @@ -19,11 +19,21 @@ function getFox (req, res, version) { let width = parseInt(req.params.width) || 400 if (width > 400) width = 400 const seed = sanitize(req.params.seed) || uuid() + const etag = `W/${seed}` + const contentType = 'image/png' + + res.set('Cache-Control', 'public; max-age=' + cacheTimeout) + res.set('Content-Type', contentType) + res.set('Etag', etag) + + if (req.headers['if-none-match'] === etag) { + res.status(304).end('') + return + } + const canvas = composeImage(width, width, seed, version) - const buffer = canvas.toBuffer('image/png') - res.set('Cache-Control', 'max-age=' + cacheTimeout) - res.set('Content-length', buffer.length) - res.type('png') + const buffer = canvas.toBuffer(contentType) + res.set('Content-Length', buffer.length) res.end(buffer, 'binary') } diff --git a/test/test.js b/test/test.js index 1a8bc22..5f1522c 100644 --- a/test/test.js +++ b/test/test.js @@ -50,6 +50,21 @@ describe('Foxy-moxy v1', () => { describe('Foxy-moxy v2', () => { describe('fox generation', () => { + it('should give 304 when presented with correct etag', (done) = async function () { + const uncachedResponse = await request(app) + .get(`/2/400/${testUID}`) + .expect('Content-Type', 'image/png') + .expect(200) + + const cachedResponse = await request(app) + .get(`/2/400/${testUID}`) + .set('If-None-Match', uncachedResponse.headers.etag) + .expect('Content-Type', 'image/png') + .expect(304) + + done() + }) + it('should respect widths < 400', (done) => { const width = 158 request(app)