UNPKG

2.44 kBJavaScriptView Raw
1require('./utils/polyfills')
2
3const pathExists = require('path-exists')
4const del = require('del')
5
6const { parsePath } = require('./path')
7const { getManifestInfo, writeManifest, removeManifest, isExpired } = require('./manifest')
8const { moveCacheFile } = require('./fs')
9const { getCacheDir } = require('./dir')
10const { list } = require('./list')
11
12// Cache a file
13const saveOne = async function(path, { move = DEFAULT_MOVE, ttl = DEFAULT_TTL, digests = [], cacheDir } = {}) {
14 const { srcPath, cachePath } = await parsePath(path, cacheDir)
15
16 if (!(await pathExists(srcPath))) {
17 return false
18 }
19
20 const { manifestInfo, identical } = await getManifestInfo({ cachePath, move, ttl, digests })
21 if (identical) {
22 return false
23 }
24
25 await del(cachePath, { force: true })
26 await moveCacheFile(srcPath, cachePath, move)
27 await writeManifest(manifestInfo)
28
29 return true
30}
31
32// Restore a cached file
33const restoreOne = async function(path, { move = DEFAULT_MOVE, cacheDir } = {}) {
34 const { srcPath, cachePath } = await parsePath(path, cacheDir)
35
36 if (!(await pathExists(cachePath))) {
37 return false
38 }
39
40 if (await isExpired(cachePath)) {
41 return false
42 }
43
44 await del(srcPath, { force: true })
45 await moveCacheFile(cachePath, srcPath, move)
46
47 return true
48}
49
50// Remove the cache of a file
51const removeOne = async function(path, { cacheDir } = {}) {
52 const { cachePath } = await parsePath(path, cacheDir)
53
54 if (!(await pathExists(cachePath))) {
55 return false
56 }
57
58 await del(cachePath, { force: true })
59 await removeManifest(cachePath)
60
61 return true
62}
63
64// Check if a file is cached
65const hasOne = async function(path, { cacheDir } = {}) {
66 const { cachePath } = await parsePath(path, cacheDir)
67
68 return (await pathExists(cachePath)) && !(await isExpired(cachePath))
69}
70
71const DEFAULT_MOVE = false
72const DEFAULT_TTL = undefined
73
74// Allow each of the main functions to take either a single path or an array of
75// paths as arguments
76const allowMany = async function(func, paths, ...args) {
77 if (!Array.isArray(paths)) {
78 return func(paths, ...args)
79 }
80
81 const results = await Promise.all(paths.map(path => func(path, ...args)))
82 return results.some(Boolean)
83}
84
85const save = allowMany.bind(null, saveOne)
86const restore = allowMany.bind(null, restoreOne)
87const remove = allowMany.bind(null, removeOne)
88const has = allowMany.bind(null, hasOne)
89
90module.exports = { save, restore, remove, has, list, getCacheDir }