import Cacheman from 'cacheman';
import { CACHE } from './Constants';
import { createCacheDirectories } from './TempDirCreator';

const formatKey = (name) => {
  if (!name) {
    throw Error('No number plate specified');
  }
  return `${CACHE.PREFIX.plate}${name}`;
};

class Cache {
  manager;

  constructor() {
    createCacheDirectories(CACHE.directory);
    this.manager = new Cacheman({
      ttl: CACHE.ttl,
      engine: CACHE.engine,
      tmpDir: CACHE.directory,
    });
  }

  async get(name) {
    return this.manager.get(formatKey(name));
  }

  save(name, data) {
    if (!data) {
      throw Error(`No data for caching car ${name}`);
    }
    this.manager.set(formatKey(name), data);
  }
}

export default Cache;
