Skip to content

Commit 3c7d6eb

Browse files
committed
Add file system cache
1 parent 8590e4c commit 3c7d6eb

File tree

3 files changed

+169
-12
lines changed

3 files changed

+169
-12
lines changed

package-lock.json

Lines changed: 141 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "bandwidth-hero-proxy",
33
"main": "server.js",
44
"private": true,
5-
"version": "1.0.2",
5+
"version": "1.0.3",
66
"description": "Data compression service that converts images to low-res WebP or JPEG on the fly. Used in Bandwidth-Hero browser extension.",
77
"author": "Anatoliy Yastreb",
88
"license": "MIT",
@@ -11,6 +11,8 @@
1111
},
1212
"dependencies": {
1313
"basic-auth": "^2.0.0",
14+
"cache-manager": "^2.6.0",
15+
"cache-manager-fs-binary": "^1.0.4",
1416
"express": "4.16.2",
1517
"lodash": "^4.17.4",
1618
"request": "^2.83.0",

src/compress.js

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,42 @@
11
const sharp = require('sharp')
22
const redirect = require('./redirect')
3+
const cacheMgr = require('cache-manager')
4+
const cacheStore = require('cache-manager-fs-binary')
5+
const cache = cacheMgr.caching({
6+
store: cacheStore,
7+
options: {
8+
ttl: 604800, //7d
9+
maxsize: 1073741824, //1GB
10+
path: './cache',
11+
preventfill: true
12+
}
13+
})
314

415
function compress(req, res, input) {
516
const format = req.params.webp ? 'webp' : 'jpeg'
17+
const key = req.params.url || ''
618

7-
sharp(input)
19+
cache.wrap(key, (callback) => {
20+
sharp(input)
821
.grayscale(req.params.grayscale)
922
.toFormat(format, {
1023
quality: req.params.quality,
1124
progressive: true,
1225
optimizeScans: true
1326
})
1427
.toBuffer((err, output, info) => {
15-
if (err || !info || res.headersSent) return redirect(req, res)
16-
17-
res.setHeader('content-type', `image/${format}`)
18-
res.setHeader('content-length', info.size)
19-
res.setHeader('x-original-size', req.params.originSize)
20-
res.setHeader('x-bytes-saved', req.params.originSize - info.size)
21-
res.status(200)
22-
res.write(output)
23-
res.end()
28+
callback(err, {binary: {output: output}, info: info})
2429
})
30+
}, (err, obj) => {
31+
if (err || !obj || !obj.info || res.headersSent) return redirect(req, res)
32+
res.setHeader('content-type', `image/${format}`)
33+
res.setHeader('content-length', obj.info.size)
34+
res.setHeader('x-original-size', req.params.originSize)
35+
res.setHeader('x-bytes-saved', req.params.originSize - obj.info.size)
36+
res.status(200)
37+
res.write(obj.binary.output)
38+
res.end()
39+
})
2540
}
2641

2742
module.exports = compress

0 commit comments

Comments
 (0)