how to modify the responses loopback sends

5,389 views
Skip to first unread message

Martin Genev

unread,
Aug 6, 2014, 7:17:13 PM8/6/14
to loopb...@googlegroups.com
I'm currently working on the loopback-ember-sdk and there are a few things I need to work out right now.

1) Ember Data insists that the responses that come from the server are in this format e.g if a model is named user the response for GET /user/{id} should be { "user" : { keys, values } } and a response to GET /users  should be { "user" : [ userModel, userModel, etc ] }.

So how can I manipulate the format of JSON which loopback returns?

2) I was able to define relationship, but only when I declared them in the model-config.json in server/root. For what I'm doing - generating models and relationships inside of ember by reading the model json files that yo generates, it would be much better if I could put my relationships in the individual json files in /common/models. I tried doing that but my relationships would not be picked up by loopback. Can I do that?

thanks

Martin Genev

unread,
Aug 6, 2014, 7:38:22 PM8/6/14
to loopb...@googlegroups.com
ignore 2) 
i got that part working

Raymond Feng

unread,
Aug 6, 2014, 9:33:24 PM8/6/14
to Martin Genev, loopb...@googlegroups.com
For 1, you should be able to use afterRemote hook for the find() methods. See http://docs.strongloop.com/display/LB/Defining+remote+hooks

Sent from my iPhone 5
--
You received this message because you are subscribed to the Google Groups "LoopbackJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to loopbackjs+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Martin Genev

unread,
Aug 7, 2014, 12:31:46 PM8/7/14
to loopb...@googlegroups.com, mge...@gmail.com
thank you, I will work with that

Miroslav Bajtoš

unread,
Aug 12, 2014, 4:39:56 AM8/12/14
to loopb...@googlegroups.com
On Thursday, August 7, 2014 1:17:13 AM UTC+2, Martin Genev wrote:
For what I'm doing - generating models and relationships inside of ember by reading the model json files that yo generates.

FWIW, I would not recommend this approach.

1. Not all models are defined via JSON files. Examples: all built-in loopback models like User, Application, Email. Models from loopback components like Installation from loopback-push.

2. Model JSON files do not contain remoting metadata. While you can generate client methods for "standard" data-access methods exposed by LoopBack out of the box,
there is no way how to generate client methods for custom model methods defined in user code, or at least I am not aware of any.

That is the reasons why the loopback-sdk-angular code generator executes the application and reads metadata from runtime.

Miroslav

Martin Genev

unread,
Aug 12, 2014, 10:12:35 AM8/12/14
to loopb...@googlegroups.com
Ah, those are valid points, thank you. Could you point me to the code where the angular sdk does this?

Miroslav Bajtoš

unread,
Aug 12, 2014, 2:47:43 PM8/12/14
to Martin Genev, loopb...@googlegroups.com
On Tue, Aug 12, 2014 at 4:12 PM, Martin Genev <mge...@gmail.com> wrote:
Ah, those are valid points, thank you. Could you point me to the code where the angular sdk does this?

Sure.

loopback-sdk-angular-cli/bin/lb-ng loads the app on the lines 20 and 24:

  var appFile = path.resolve(argv._[0]);
  var app = require(appFile);

The code generator in loopback-sdk-angular/lib/services.js#L28 processes the remoting metadata from the app object and builds a structure that can be (more) easily consumed from the EJS template lib/services.template

  app.handler('rest').adapter.getClasses().forEach(function(c) {
    // process the class (Model) metadata
  });
    
There is a bit of magic involved to generate correct $resource definition for methods created by model relations (e.g. Product.categories or Product.categories.unlink), you should be able to find it in those two source files.

Note:

This approach requires that the main application file must export the app object created by calling `var app = loopback()` and the app should not be started unless the file is the main module. Both the old generators (slc loopback project) and new generators (slc loopback:app/yo loopback:app) generate code that meets these requirements.
 
Miroslav

adam wilson

unread,
Sep 20, 2014, 11:45:35 AM9/20/14
to loopb...@googlegroups.com, mge...@gmail.com
I'm trying out Loopback for a project that will use Ember as its front-end, and following this advice I can't get it to output the required JSON format. 

E.g. in my Account model I have: 

module.exports = function(Account) {
    Account.afterRemote('**', function (ctx, account, next) {
      if(ctx.result) {
        if(Array.isArray(ctx.result)) {
          ctx.res.body = { 'accounts': account };
        } else {
          ctx.res.body = { 'account': account };
        }
      }
      
      console.log(ctx.res.body);
      
      next();
    });
};

This outputs the correct JSON to the console but not in the response. 
Would be much better to have a general JSON formatter / serialiser, that adjusted the requests and responses to follow a given format when needed. 

Matthew Williams

unread,
Nov 5, 2014, 5:41:13 PM11/5/14
to loopb...@googlegroups.com, mge...@gmail.com
I am having the same issue.  I would like to override the rest api to include root objects that are named for the routes as in the original question.  Was there a solution for this? 

Raymond Feng

unread,
Nov 5, 2014, 5:50:02 PM11/5/14
to Matthew Williams, loopb...@googlegroups.com, mge...@gmail.com
You should reset ctx.result instead of cx.res.body as the body will be overwritten later based on the Accept header.

Thanks,

---
Raymond Feng
Co-Founder and Architect @ StrongLoop, Inc.

StrongLoop makes it easy to develop APIs in Node, plus get DevOps capabilities like monitoring, debugging and clustering.

Alan Jackson

unread,
Feb 14, 2015, 4:58:32 PM2/14/15
to loopb...@googlegroups.com, matth...@gmail.com, mge...@gmail.com
Raymond

This is extremely helpful, and I had success connecting with my Ember client using the methods described above for creating a remote hook. I have on additional requirement in my case. I have created a relationship in my case for "Project hasMany Issues" for an issue tracker type application. Therefore the response for GET Projects/{id}/issues in my case should not return a named root of "Projects" but rather of "Issues". I have opted to define the method name rather than use the wildcard. See below. However I can not determine the method name created by loopback after creating the hasMany relationship. I have tried both 'prototype_get_issues' and 'get_issues' as well as 'issues'. Is there documentation on the correct method name to use here if this is event he correct approach.


module.exports = function(Project) {

 
Project.afterRemote('find', function(ctx, project, next) {
   
if(ctx.result) {
      ctx
.result = {'projects': project};
   
}
   
next();
 
});

 
Project.afterRemote('findById', function(ctx, project, next) {
   
if(ctx.result) {
      ctx
.result = {'project': project};
   
}
   
next();
 
});

 
Project.afterRemote('prototype_get_issues', function(ctx, issue, next) {
   
if(ctx.result) {
      ctx
.result = {'issues': issue};
   
}
   
next();
 
});

};

Thanks,

Alan Jackson
Reply all
Reply to author
Forward
0 new messages