Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Last active October 15, 2022 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidWells/bcd2f746a4f3c59a01094617b96d4343 to your computer and use it in GitHub Desktop.
Save DavidWells/bcd2f746a4f3c59a01094617b96d4343 to your computer and use it in GitHub Desktop.
const fs = require('fs')
const path = require('path')
const cacheManager = require('cache-manager')
const fsStoreHash = require('cache-manager-fs-hash')
const CACHE_KEY = 'foo'
const STORAGE_PATH = (process.env.IS_OFFLINE) ? path.join(__dirname, '../tmp') : '/tmp'
const SECONDS = 60
const MINUTES = 60
const ONE_HOUR = SECONDS * MINUTES
const mbOfStorage = 512
/* initialize caching on disk */
const diskCache = cacheManager.caching({
store: fsStoreHash,
options: {
/* TTL in seconds */
ttl: ONE_HOUR,
/* max size in bytes on disk */
// maxsize: mbOfStorage * 1000 * 1000,
path: STORAGE_PATH,
}
})
async function usage() {
const hasCache = await diskCache.get(CACHE_KEY)
if (hasCache && hasCache.length) {
/* If cache NOT empty return it */
// console.log('Using cached value', hasCache)
return hasCache
}
// else do fetch
const data = await getStuff()
// Then save cache
console.log('Saving value')
await diskCache.set(CACHE_KEY, data)
}
function getCacheSize(filePath) {
return new Promise((resolve, reject) => {
fs.stat(filePath, (err, stats) => {
if (err) {
return resolve({ sizeInBytes: 0, sizeInMB: 0 })
}
const byteSize = stats.size
const megaByteSize = byteSize / (1024 * 1024)
return resolve({
sizeInBytes: byteSize,
sizeInMB: megaByteSize
})
})
})
}
{
"dependencies": {
"cache-manager": "^3.4.0",
"cache-manager-fs-hash": "0.0.9"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment