-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
67 lines (59 loc) · 1.81 KB
/
index.js
File metadata and controls
67 lines (59 loc) · 1.81 KB
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
57
58
59
60
61
62
63
64
65
66
67
const flatCache = require('flat-cache')
const fs = require('fs-extra')
const path = require('path')
const {
success,
warning,
info
} = require('log-symbols')
const chalk = require('chalk')
const isEmptyObj = (obj) => Object.keys(obj).length === 0
const fetchData = async (cache, filePath) => {
const fetchFn = require(filePath)
const data = await fetchFn()
const stringifiedData = JSON.stringify(data)
cache.setKey(filePath, stringifiedData)
cache.setKey(`${filePath}-timestamp`, new Date().getTime())
cache.save()
return {
'.json': stringifiedData
}
}
const fetchWarning = (filePath) => {
console.info(
chalk.yellow('!', `Data of ${filePath} has been fetched from external source.`)
)
}
module.exports = function (snowpackConfig, pluginOptions) {
const { scriptSuffix, cacheDuration = 86400000, cachePath } = pluginOptions
const cache = flatCache.load('prefetchData', cachePath)
return {
name: 'prefetch-data',
resolve: {
input: ['.js'],
output: ['.json']
},
async load ({ fileExt, filePath }) {
if (scriptSuffix.test(filePath)) {
if (isEmptyObj(cache._persisted)) {
fetchWarning(filePath)
return await fetchData(cache, filePath)
}
const previousFetchTimestamp = cache.getKey(`${filePath}-timestamp`)
const currentTimestamp = new Date().getTime()
const timePassedSinceLastBuild = currentTimestamp - previousFetchTimestamp
if (timePassedSinceLastBuild > cacheDuration) {
fetchWarning(filePath)
return await fetchData(cache, filePath)
}
const cachedData = cache.getKey(filePath)
console.info(
success, chalk.green(`Data of ${filePath} has been served from cache.`)
)
return {
'.json': cachedData
}
}
}
}
}