Last active
September 9, 2016 13:08
-
-
Save sebald/4af5cbadfeca5fb732bfc7a115a8f8f0 to your computer and use it in GitHub Desktop.
Read async from lowdb
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 { exists, readFile, writeFile } from 'graceful-fs'; | |
import { parse } from 'json-parse-helpfulerror'; | |
import fileAsync from 'lowdb/lib/file-async'; | |
/** | |
* Custom storage for `lowdb`, b/c we want to have read AND | |
* write to be async. This will make the API more easy to use. | |
*/ | |
const storage = { | |
read: file => { | |
return new Promise((resolve, reject) => { | |
// Asynchronously read database and parse JSON to `object`. | |
function readDatabase () { | |
readFile(file, 'utf8', (err, data) => { | |
if (err) { return reject(err); } | |
try { | |
resolve(parse(data.trim() || '{}')); | |
} | |
catch (e) { | |
if (e instanceof SyntaxError) { | |
e.message = `Malformed JSON in file: ${file}\n${e.message}`; | |
} | |
reject(e); | |
} | |
}); | |
} | |
// Asynchronously create an empty database (JSON file). | |
function initEmptyDatabase () { | |
writeFile(file, '{}', err => { | |
if (err) { return reject(err); } | |
resolve({}); | |
}); | |
} | |
// Depending if the file exists, we read it or create an empty | |
// database. | |
exists(file, result => result ? readDatabase() : initEmptyDatabase()); | |
}); | |
}, | |
write: fileAsync.write | |
}; | |
export default storage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NOTE: This forces you to always do
db.read
/db.write
, but the API still is not really async/promise-based. E.g.getState
is still synchronous ...