Handle Etag and If-none-match headers and 304 responses

This commit is contained in:
Liran Nuna 2018-10-22 11:41:29 -07:00
parent a674d6a79c
commit 1b95c4c794
2 changed files with 29 additions and 4 deletions

View file

@ -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')
}

View file

@ -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)