Created
June 6, 2021 12:12
-
-
Save melbourne2991/41dfb58b5948de8a3f6b7a56f96324aa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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