What is the "StrongLoop way" for chaining Model find calls while keeping modularity?

22 views
Skip to first unread message

Akram Shehadi

unread,
Apr 25, 2016, 12:41:03 PM4/25/16
to StrongLoop
Hello everyone,

I would like to ask for your opinion on what is the StrongLoop way for chaining calls to Model.find, findById, etc while keeping modularity, i.e. functions in different files, etc?

The problem is that as far as I can tell, since all Model.find* calls are async (and thus you need to pass in the callback to be executed after the query results return), chaining several finds one after another would imply a callback hell almost by definition I believe, since we would need to run the first async1 call and pass cb1 call, then inside cb1 call async2 and pass cb2, inside cb2 call async3, etc.

So I looked up ways to avoid cb hell and one of the first suggestions is to modularize code and avoid anonymous functions if possible (to both have cleaner code and to have function names in the error stack trace), and the other one is to use things like promises, generators and other solutions.

However... and here's my dilemma: StrongLoop supports promises up to a point, i.e. it's not yet 100% promises aware. So if I go down this route (which I think would be the best, since it seems promises are a good improvement over having nested cb's) I might solve the issue but also encounter a lot of others if I need to do something that's not yet supported, and I don't think I have yet the knowledge and skill to mess with the StrongLoop framework source to fix it if the need arises.

My question is then, is there a pattern or other known way of structuring code such that you are able to modularize and at the same time allow chanined async calls to happen without having a cb hell?

------------

And to avoid the XY Problem I will state that the actual problem I want to solve is building a sort of permission system (Because StrongLoop's built in one is not fine grained enough for our purposes (we are already using it for the coarse part of authorization, but need better per-instance control and not just per-endpoint, etc). So my solution is to do something like the following, in the beforeRemote remote hook so it applies for every request, and it gets executed after StrongLoop's ACL:

var role = getUserRole(userId);
var perms = getEndpointPermissionRequirements(endpointPath);

var isAuthorized = matchesPermissions(role, perms);

return isAuthorized;

However like I said, I can't run a getX and then call a getY. I need to pass the getY as a cb to getX, and so on.

Is there a pattern to avoid this? or am I just doing it the wrong way and I just need to structure it differently to avoid this? how?

Any resources I can read about it?

Thanks!


sim...@ca.ibm.com

unread,
Apr 26, 2016, 9:42:22 PM4/26/16
to StrongLoop

Please post LoopBack questions at https://groups.google.com/forum/#!forum/loopbackjs
Reply all
Reply to author
Forward
0 new messages