I am currently working on figuring out the best approach for chaining conditional queries in my project.
Let me break down my scenario using some pseudo-code:
We first need to check if an item exists;
if it doesn't:
respond with a status of 404;
if it does:
then we check if the current user is the owner of the item;
if they are not:
redirect them to another page;
if they are:
fetch the details of the item and display the page;
Initially, I thought about using tasks to maintain the same connection. However, due to the various possible outcomes, I am facing challenges in effectively handling promises:
db.task(t => {
return t.items.exists(itemId)
.then(exists => {
if (!exists) { // item does not exist
// handle 404 response here
}
return t.items.isOwner(itemId, userId)
.then(isOwner => {
if (!isOwner) {
// redirect to another page
}
return t.items.getById(itemId);
})
})
})
.then(data => {
// Process and render data
})
.catch(console.error); // Handle unexpected errors
In case I attempt to redirect to a 404 page, the promise will still be resolved afterwards. Another alternative would involve:
if (!exists) { // item does not exist
return Promise.reject('404');
}
...
.then(data => {
// Successfully process and render data
}, reason => {
// Conditions were not met as expected
})
This 'works', however, it captures both errors and unmet conditions. I am aiming for a more specific handler dedicated to unmet conditions.
Another idea I considered is:
var p = db.task(t => {
return t.items.exists(itemId)
.then(exists => {
if (!exists) { // item does not exist
// Resolve p (and break promise chain) by
// calling something like p.resolve(() => {
// return res.redirect...
// });
}
return t.items.isOwner(itemId, userId);
})
.then(isOwner => {
if (!isOwner) {
// Resolve p and redirect to another page
}
return t.items.getById(itemId);
})
.then(item => {
// Everything is fine, resolve with a handler to show the page
});
})
.then(action => {
action();
})
.catch(console.error); // Handle unexpected errors
However, I am unsure how to resolve p
. Calling Promise.resolve(...)
within a nested promise resolves the subsequent promise before reaching p
's then
.
What is the recommended practice for chaining conditional queries and managing multiple outcomes in pg-promise
while maintaining performance efficiency?