Skip to content

Commit 856f3ec

Browse files
authored
add 60 second cache (projectwallace#15)
* add 60 second cache * add log to verify that item is taken from cache * fix cache age * rm log line
1 parent ad671e0 commit 856f3ec

File tree

4 files changed

+41
-10
lines changed

4 files changed

+41
-10
lines changed

index.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@ const got = require('got')
22
const chromium = require('chrome-aws-lambda')
33
const normalizeUrl = require('normalize-url')
44
const isUrl = require('is-url')
5+
const LRU = require('lru-cache')
6+
7+
const cssCache = new LRU({
8+
max: 500,
9+
maxAge: 60 * 1000
10+
})
511

612
const extractCss = async url => {
713
const browser = await chromium.puppeteer.launch({
@@ -76,13 +82,20 @@ module.exports = async (req, res) => {
7682
)
7783
}
7884

85+
if (cssCache.has(url)) {
86+
res.setHeader('Content-Type', 'text/css')
87+
res.statusCode = 200
88+
return res.end(cssCache.get(url))
89+
}
90+
7991
try {
8092
const css = url.endsWith('.css')
8193
? (await got(url)).body
8294
: await extractCss(url)
8395

8496
res.setHeader('Content-Type', 'text/css')
8597
res.statusCode = 200
98+
cssCache.set(url, css)
8699
return res.end(css)
87100
} catch (error) {
88101
res.statusCode = 500

package-lock.json

Lines changed: 25 additions & 10 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"chrome-aws-lambda": "^1.19.0",
1616
"got": "^9.6.0",
1717
"is-url": "^1.2.4",
18+
"lru-cache": "^5.1.1",
1819
"normalize-url": "^4.3.0",
1920
"puppeteer": "^1.19.0",
2021
"puppeteer-core": "^1.18.1"

public/index.html

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ <h2>Example request urls:</h2>
6565
</li>
6666
</ul>
6767

68+
<p>Please note that there is a 1 minute cache for each (normalized) url.</p>
69+
6870
<p>
6971
Source code
7072
<a href="https://github.com/bartveneman/extract-css" rel="noopener"

0 commit comments

Comments
 (0)