Skip to content

Instantly share code, notes, and snippets.

@AlbinoDrought
Created February 17, 2021 17:20
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 AlbinoDrought/3a15a87cda289b6c7c32a144f17aae54 to your computer and use it in GitHub Desktop.
Save AlbinoDrought/3a15a87cda289b6c7c32a144f17aae54 to your computer and use it in GitHub Desktop.
Persistent cachios + lru-cache usage for https://github.com/AlbinoDrought/cachios/issues/59
const axios = require('axios');
const cachios = require('cachios');
const LRU = require('lru-cache');
const fs = require('fs');
//// this part is for debugging purposes:
// build an axios client that logs outbound requests
const axiosClient = axios.create();
axiosClient.interceptors.request.use((config) => {
console.log('uncached outbound request to', config.url);
return config;
});
// use it in our cachios client
const cachiosClient = cachios.create(axiosClient);
//// this part is for https://github.com/AlbinoDrought/cachios/issues/59
// configure our cachios client with custom cache
const customCache = new LRU(500);
cachiosClient.cache = customCache;
// load cache from cache.json into lru-cache instance
const readCache = (lruCache) => new Promise((resolve, reject) => {
fs.readFile('cache.json', 'utf8', (err, data) => {
if (err) {
return reject(err);
}
try {
const parsedCache = JSON.parse(data);
lruCache.load(parsedCache);
return resolve();
} catch (ex) {
return reject(ex);
}
});
});
// dump cache from lru-cache instance into cache.json
const writeCache = (lruCache) => new Promise((resolve, reject) => {
const data = JSON.stringify(lruCache.dump());
fs.writeFile('cache.json', data, null, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
})
});
(async () => {
// load cache on boot once
try {
await readCache(customCache);
console.log('read', customCache.itemCount, 'items from disk');
} catch (ex) {
console.error('error reading cache (probably the first uncached run), continuing', ex);
}
// make our requests
await cachiosClient.get('http://example.com/');
await cachiosClient.get('http://example.com/');
await cachiosClient.get('http://example.com/');
// write cache on process end
await writeCache(customCache);
// alternatively, write cache automatically:
// setInterval(() => writeCache(customCache), 30000);
})();
{
"license": "PUBLIC DOMAIN",
"dependencies": {
"axios": "^0.21.1",
"cachios": "^2.2.5",
"lru-cache": "^6.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment