import { Databases, getConnection } from '../../core/database';
import { StoreValue } from '../../entities/store/store-value';

const CACHE_ID = 'store';

export async function load(key: StoreKey): Promise<any> {
  const c = await getConnection(Databases.STORE);
  const repository = c.getRepository(StoreValue);
  const storeValue = await repository.findOne(key, {
    cache: {
      id: CACHE_ID,
      milliseconds: 0,
    },
  });
  return storeValue.value;
}

export async function save(key: StoreKey, data: any): Promise<void> {
  const c = await getConnection(Databases.STORE);
  const manager = c.manager;
  const storeValue = new StoreValue();
  storeValue.key = key;
  storeValue.value = data;
  await manager.save(storeValue);
  await c.queryResultCache.remove([CACHE_ID]);
}
