@vendure/ngx-translate-extract
Version:
Extract strings from projects using ngx-translate
70 lines (69 loc) • 2.31 kB
JavaScript
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const getHash = (value) => crypto.createHash('sha256').update(value).digest('hex');
export class FileCache {
cacheFile;
tapped = {};
cached = undefined;
originalCache;
versionHash;
constructor(cacheFile) {
this.cacheFile = cacheFile;
}
get(uniqueContents, generator) {
if (!this.cached) {
this.readCache();
this.versionHash = this.getVersionHash();
}
const key = getHash(`${this.versionHash}${uniqueContents}`);
if (key in this.cached) {
this.tapped[key] = this.cached[key];
return this.cached[key];
}
return (this.tapped[key] = generator());
}
persist() {
const newCache = JSON.stringify(this.sortByKey(this.tapped), null, 2);
if (newCache === this.originalCache) {
return;
}
const file = this.getCacheFile();
const dir = path.dirname(file);
const stats = fs.statSync(dir, { throwIfNoEntry: false });
if (!stats) {
fs.mkdirSync(dir);
}
const tmpFile = `${file}~${getHash(newCache)}`;
fs.writeFileSync(tmpFile, newCache, { encoding: 'utf-8' });
fs.rmSync(file, { force: true, recursive: false });
fs.renameSync(tmpFile, file);
}
sortByKey(unordered) {
return Object.keys(unordered)
.sort()
.reduce((obj, key) => {
obj[key] = unordered[key];
return obj;
}, {});
}
readCache() {
try {
this.originalCache = fs.readFileSync(this.getCacheFile(), { encoding: 'utf-8' });
this.cached = JSON.parse(this.originalCache) ?? {};
}
catch {
this.originalCache = undefined;
this.cached = {};
}
}
getVersionHash() {
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const packageJson = fs.readFileSync(path.join(projectRoot, 'package.json'), { encoding: 'utf-8' });
return getHash(packageJson);
}
getCacheFile() {
return `${this.cacheFile}-ngx-translate-extract-cache.json`;
}
}