mapycz-api
Version:
mapy.cz fastrpc and REST interfaces
54 lines • 1.36 kB
JavaScript
import * as fs from 'fs';
import * as fsp from 'fs/promises';
import { md5 } from 'js-md5';
import path from 'path';
import logger from './logger.js';
export class Cache {
key(obj) {
return md5(JSON.stringify(obj));
}
is(_key) {
return false;
}
async get(_key) { }
async set(_key, _value) { }
}
export class InMemoryCache extends Cache {
constructor() {
super();
this.store = {};
}
is(key) {
return key in this.store;
}
async get(key) {
return this.store[key];
}
async set(key, value) {
this.store[key] = value;
}
}
export class FileCache extends Cache {
constructor(cachePath = 'cache') {
super();
this.cachePath = cachePath;
if (!fs.existsSync(cachePath))
throw Error(`cache path:${cachePath} doesn't exist`);
}
is(key) {
return fs.existsSync(this.path(key));
}
path(key) {
return path.join(this.cachePath, key);
}
async get(key) {
logger.debug({ key }, 'cache read');
const buffer = await fsp.readFile(this.path(key), 'utf8');
return JSON.parse(buffer);
}
async set(key, value) {
logger.debug({ key }, 'cache write');
return fsp.writeFile(this.path(key), JSON.stringify(value));
}
}
//# sourceMappingURL=cache.js.map