Ghost/core/server/services/url/LocalFileCache.js
Naz ee4d2dd1a8 Extracted a local file cache class for URLs
refs https://github.com/TryGhost/Toolbox/issues/135

- This extracts the file storage knowledge out of the URL Service an allows to have optional features based on the environment - for example turning off writing cache for when running tests
2021-11-22 21:56:32 +13:00

70 lines
1.8 KiB
JavaScript

const fs = require('fs-extra');
const path = require('path');
class LocalFileCache {
/**
* @param {Object} options
* @param {String} options.storagePath - cached storage path
*/
constructor({storagePath}) {
const urlsStoragePath = path.join(storagePath, 'urls.json');
const resourcesCachePath = path.join(storagePath, 'resources.json');
this.storagePaths = {
urls: urlsStoragePath,
resources: resourcesCachePath
};
}
/**
* 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) {
return fs.writeFile(this.storagePaths[type], JSON.stringify(data, null, 4));
}
}
module.exports = LocalFileCache;