This is a simple repository where I want to save all the invoices of some queried users. I wanted this module to only expose a simple saveInvoices
method and return a Promise.
As a DB, I use Firebase whose API is async but does not return standard JS promises so I promisify the db queries.
I haven't yet taken every reject and fail scenarios into account. Looking forward to read your feedback.
const _ = require('lodash');
const Firebase = require('firebase');
const Config = require('./../../shared/config');
const Repository = (function() {
let _conn;
const _connect = function() {
return new Promise((resolve, reject) => {
_conn = new Firebase(Config.FIREBASESERVER);
_conn.authWithCustomToken(Config.FIREBASESECRET, () => {
resolve();
});
});
};
const _getQueuedUsers = function() {
return new Promise((resolve, reject) => {
_conn.child('users')
.orderByChild('nextInvoiceDate')
.startAt(1)
.endAt(Date.now())
.once('value', (usersSnap) => {
resolve(_.values(usersSnap.val()));
});
});
};
const _saveInvoice = function(user) {
return new Promise((resolve, reject) => {
// ...
resolve();
});
};
const saveInvoices = function() {
return new Promise((resolve, reject) => {
_connect()
.then(() => _getQueuedUsers())
.then((users) => {
resolve(Promise.all(users.map((u) => _saveInvoice(u))));
}, (rejection) => {
console.log(rejection);
});
});
};
return {
saveInvoices
}
})();
Repository.saveInvoices
.then(() => { console.log('done'); })
.catch((err) => { console.error(err); });