Loopback tip of the day: Nest Remoting

Brainfock uses Loopback framework at backend, which is an extension of ExpressJS and is really, really good for building REST APIs, allowing me to focus more on app business logic.

It is easy to create API endpoint to get info about any model, or get list of related models.

Consider the following: application has Workspace and Topic models. Each topic belongs to a workspace, and some topics may also be nested under parent topic.

Following documentation, in just a few minutes you can easily have these rest endpoints:

  • api/workspaces/123 — for info about workspace id 123
  • api/workspaces/123/topics — for list of topics inside of workspace 123
  • api/workspaces/123/topics/321 — to get topic id 321 that also belongs to workspace 123

Now, do you see where this is going?

I needed a way to also list topics of a topic of a workspace:

api/workspaces/123/topics/321/topics

This did not work on it’s own (thank God!), but, as it turns out, there is an undocumented way to achieve this with Loopback: nest remoting.

So, how do you list models of a related model over REST API with Loopback?

I have to take a small step back and thank Loopback community (mainly residing at Gitter/Loopback) for being friendly, helpful and really professional!

So, to enable nest remoting, in my case, I had to call `nestRemoting` method from Workspace model and allow to access topics like this:

models/workspace.js:

module.exports = function(Workspace) {
  Workspace.on('attached', function() {
    Workspace.nestRemoting('topics');
  });
};

Now, I have REST endpoint api/workspaces/123/topics/321/topics

Advertisements
Loopback tip of the day: Nest Remoting