Reputation: 1412
I am writing a small application and which communicates with the DB, instead of using callback pattern I am using Promises to simplify my code. Having done a fair amount of coding I can now see some pattern very frequently in my code, I need to know how can I refactor it so that the similar logic is at a single place.
var queryString = "select * from users u inner join "+
"(select user_id, count(id) cnt from applications "+
"where id in (select id from applications where "+
"created_at > current_date - interval '1 week') "+
"group by user_id) a on u.id = a.user_id order by a.cnt desc";
var self = this;
return new Promise(function _promise(resolve, reject) {
req.client.query(queryString, [], function result(error, result) {
req.done(error);
if (error) {
console.log('error ' + error.message);
return reject(error);
}
var users = result.rows.map(function(row) {
return new User(row);
});
resolve(users);
});
});
The above pattern is my every method the only thing that varies is the content after if
, is there any functional approach I can use to refactor it out?
Adding one more example:
var queryString = 'select c.id, c.name, t.contact_user '+
'from companies c, teams t '+
'where t.user_id = $1::int and t.company_id = c.id '+
'limit $2::int';
var self = this;
return new Promise(function _promise(resolve, reject) {
req.client.query( queryString, [self.id, User._RESOURCE_LIMIT],
function result(error, result) {
req.done(error);
if (error) {
console.log('Error ' + error.message);
return reject(error);
}
self._companies = result.rows.map(function (data) {
return new Company(data);
});
resolve(self);
});
});
Upvotes: 0
Views: 245
Reputation: 4523
You can do something like this:
function queryDb(queryString, arr) {
var arr = arr || [];
return new Promise(function _promise(resolve, reject) {
req.client.query(queryString, arr, function result(error, result) {
req.done(error);
if (error) {
console.log('Error ' + error.message);
return reject(error);
}
resolve(result);
});
});
}
queryDb("queryString", arr).then(function(response){ //calling the function everytime like this
//do stuff here
}, function(error){
//handle error
})
Upvotes: 0
Reputation: 1
Promisified "query" function
let query = (req, queryString, arg = []) => new Promise((resolve, reject) => {
req.client.query(queryString, arg, (error, result) => {
req.done(error);
if (error) {
return reject(error);
}
resolve(result);
});
});
Usage (as per example in the question)
query(req, "select * .... etc")
.then(result => {
return result.rows.map(function(row) {
return new User(row);
});
})
.catch(reason => {
// error handling goes here
});
Upvotes: 1