Skip to content

Instantly share code, notes, and snippets.

@sebald
Last active September 9, 2016 13:08
Show Gist options
  • Save sebald/4af5cbadfeca5fb732bfc7a115a8f8f0 to your computer and use it in GitHub Desktop.
Save sebald/4af5cbadfeca5fb732bfc7a115a8f8f0 to your computer and use it in GitHub Desktop.
Read async from lowdb
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;
@sebald
Copy link
Author

sebald commented Sep 9, 2016

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 ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment