Skip to content

Instantly share code, notes, and snippets.

@melbourne2991
Created June 6, 2021 12:12
Show Gist options
  • Save melbourne2991/41dfb58b5948de8a3f6b7a56f96324aa to your computer and use it in GitHub Desktop.
Save melbourne2991/41dfb58b5948de8a3f6b7a56f96324aa to your computer and use it in GitHub Desktop.
import {promises as fs} from 'fs';
import path from 'path';
const JsonStore = <T>(filename: string, initial: T) => {
const filePath = path.resolve(__dirname, filename);
const api = {
read: async (): Promise<T> => {
if((await fs.stat(filePath)).isFile()) {
return JSON.parse(await fs.readFile(filePath, 'utf8'));
}
return initial;
},
write: async (value: T) => {
return fs.writeFile(filePath, JSON.stringify(value))
},
update: async (callback: (value: T) => T) => {
const prev = await api.read();
await api.write(callback(prev))
}
}
return api;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment