diff --git a/src/api.js b/src/api.js index 8285d3c..81ef562 100644 --- a/src/api.js +++ b/src/api.js @@ -19,19 +19,27 @@ module.exports = { throw Boom.badRequest('Invalid URL') } - const img = await ipx.get({ format, operations, src }) - const response = h.response(img.data) - - if (img.cacheKey) { - response.etag(etag(img.cacheKey).replace(/"/g, ''), { vary: 'Origin' }) - } - - if (img.stats.mtime) { - response.header('last-modified', img.stats.mtime.toUTCString()) + // Get basic info about request + const info = await ipx.getInfo({ format, operations, src }) + + // Sets the response 'ETag' and 'Last-Modified' headers and + // checks for any conditional request headers to decide + // if the response is going to qualify for an HTTP 304 (Not Modified) + // https://hapijs.com/api#-hentityoptions + let response = h.entity({ + etag: etag(info.cacheKey).replace(/"/g, ''), + modified: info.stats.mtime + }) + + // Get real response + if (!response) { + const data = await ipx.getData(info) + response = h.response(data) } - if (img.format) { - response.type('image/' + img.format) + // Set additional headers + if (info.format) { + response.type('image/' + info.format) } else { response.type('image') } diff --git a/src/ipx.js b/src/ipx.js index db0c708..d532175 100644 --- a/src/ipx.js +++ b/src/ipx.js @@ -101,13 +101,7 @@ class IPX { }) } - /** - * Convert and get the result - * @param {String} format - * @param {String} operations - * @param {String} src - */ - async get ({ format, operations, src }) { + async getInfo ({ format, operations, src }) { // Validate format if (format === '_') { format = extname(src).substr(1) @@ -146,15 +140,21 @@ class IPX { const statsKey = stats.mtime.getTime().toString(16) + '-' + stats.size.toString(16) const cacheKey = src + '/' + statsKey + '/' + operationsKey + '.' + format + // Return info + return { + operations: _operations, + stats, + cacheKey, + format, + src + } + } + + async getData ({ cacheKey, stats, operations, format, src }) { // Check cache existence const cache = await this.cache.get(cacheKey) if (cache) { - return { - format, - data: cache, - stats, - cacheKey - } + return cache } // Read buffer from input @@ -167,7 +167,7 @@ class IPX { sharp = sharp.toFormat(format) } - _operations.forEach(({ operation, args }) => { + operations.forEach(({ operation, args }) => { try { sharp = operation.handler(this, sharp, ...args) } catch (e) { @@ -187,12 +187,7 @@ class IPX { console.error(e) } - return { - data, - format, - stats, - cacheKey - } + return data } async cleanCache () {