-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
56 lines (49 loc) · 1.51 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const nfetch = require('node-fetch')
const NodeCache = require('node-cache');
const cache = new NodeCache();
const headersSubSetKeys = ['server', 'date', 'content-type', 'content-length']
const getHeadersSubset = headers => Object.keys(headers)
.filter((key) => headersSubSetKeys.indexOf(key) >= 0)
.reduce((subset, key) => Object.assign(
subset, { [key]: headers[key] }), {})
const fetchLive = url => {
return nfetch(url)
.then(r => {
return {
buffer: r.buffer(),
headers: getHeadersSubset(r.headers.raw()),
type: r.headers.get('content-type'),
status: r.status
}
})
}
const renderContent = (buffer, mtype) => {
if ((mtype || '').includes('text/html')) {
return buffer.toString('utf-8')
} else if ((mtype || '').includes('application/json')) {
return JSON.parse(buffer.toString('utf-8'))
}
return buffer
}
const cacheRenderBuffer = (url, replyObj, ttl, cached = false) => {
if (replyObj.status === 200 && !cached) cache.set(url, replyObj, ttl)
return replyObj.buffer.then(x => ({
reply: renderContent(x, replyObj.type),
headers: replyObj.headers,
status: replyObj.status,
cached
}))
}
const fetch = (url, ttl) => {
return cache.get(url)
? Promise.resolve(cache.get(url))
.then(r => cacheRenderBuffer(url, r, null, true))
: fetchLive(url)
.then(r => cacheRenderBuffer(url, r, ttl))
}
const fetchFresh = (url, ttl) => fetchLive(url)
.then(r => cacheRenderBuffer(url, r, ttl))
module.exports = {
fetch,
fetchFresh
}