UNPKG

@graphql-mesh/cache-file

Version:
44 lines (41 loc) 1.39 kB
import { path } from '@graphql-mesh/cross-helpers'; import DataLoader from 'dataloader'; import { pathExists, writeJSON } from '@graphql-mesh/utils'; class FileCache { constructor({ path: path$1, importFn }) { this.absolutePath = path.isAbsolute(path$1) ? path$1 : path.join(process.cwd(), path$1); this.json$ = pathExists(this.absolutePath).then(async (isExists) => { if (isExists) { const existingData = await importFn(this.absolutePath); return { ...existingData, }; } return {}; }); this.writeDataLoader = new DataLoader(async (keys) => { const json = await this.json$; await writeJSON(this.absolutePath, json); return keys; }); } async getKeysByPrefix(prefix) { const json = await this.json$; return Object.keys(json).filter(key => key.startsWith(prefix)); } async get(name) { const json = await this.json$; return json[name]; } async set(name, value) { const json = await this.json$; json[name] = value; await this.writeDataLoader.load(name); } async delete(name) { const json = await this.json$; delete json[name]; await this.writeDataLoader.load(name); } } export default FileCache;