2021-11-18 14:42:56 +03:00
|
|
|
const fs = require('fs-extra');
|
|
|
|
const path = require('path');
|
|
|
|
|
|
|
|
class LocalFileCache {
|
|
|
|
/**
|
|
|
|
* @param {Object} options
|
|
|
|
* @param {String} options.storagePath - cached storage path
|
2021-11-18 15:01:57 +03:00
|
|
|
* @param {Boolean} options.writeDisabled - controls if cache can write
|
2021-11-18 14:42:56 +03:00
|
|
|
*/
|
2021-11-18 15:01:57 +03:00
|
|
|
constructor({storagePath, writeDisabled}) {
|
2021-11-18 14:42:56 +03:00
|
|
|
const urlsStoragePath = path.join(storagePath, 'urls.json');
|
|
|
|
const resourcesCachePath = path.join(storagePath, 'resources.json');
|
|
|
|
|
|
|
|
this.storagePaths = {
|
|
|
|
urls: urlsStoragePath,
|
|
|
|
resources: resourcesCachePath
|
|
|
|
};
|
2021-11-18 15:01:57 +03:00
|
|
|
this.writeDisabled = writeDisabled;
|
2021-11-18 14:42:56 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handles reading and parsing JSON from the filesystem.
|
|
|
|
* In case the file is corrupted or does not exist, returns null.
|
|
|
|
* @param {String} filePath path to read from
|
|
|
|
* @returns {Promise<Object>}
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
async readCacheFile(filePath) {
|
|
|
|
let cacheExists = false;
|
|
|
|
let cacheData = null;
|
|
|
|
|
|
|
|
try {
|
|
|
|
await fs.stat(filePath);
|
|
|
|
cacheExists = true;
|
|
|
|
} catch (e) {
|
|
|
|
cacheExists = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (cacheExists) {
|
|
|
|
try {
|
|
|
|
const cacheFile = await fs.readFile(filePath, 'utf8');
|
|
|
|
cacheData = JSON.parse(cacheFile);
|
|
|
|
} catch (e) {
|
|
|
|
//noop as we'd start a long boot process if there are any errors in the file
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return cacheData;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {'urls'|'resources'} type
|
|
|
|
* @returns {Promise<Object>}
|
|
|
|
*/
|
|
|
|
async read(type) {
|
|
|
|
return await this.readCacheFile(this.storagePaths[type]);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {'urls'|'resources'} type of data to persist
|
|
|
|
* @param {Object} data - data to be persisted
|
|
|
|
* @returns {Promise<Object>}
|
|
|
|
*/
|
|
|
|
async write(type, data) {
|
2021-11-18 15:01:57 +03:00
|
|
|
if (this.writeDisabled) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2021-11-18 14:42:56 +03:00
|
|
|
return fs.writeFile(this.storagePaths[type], JSON.stringify(data, null, 4));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = LocalFileCache;
|