0
votes

I am using Loopback for a node JS app. Loopback auto generates the CRUD api. So, I was trying to alter one get api so also include a table. I can do this by adding include filter in query as

/api/expensecategories?filter[include]=vendors

but I want /api/expensecategories to return with the table. For that I used beforeRemote() method to change the request before.

My code for it is:

expensecategories.beforeRemote('find', function (ctx, inst, next) {
   console.log(ctx.req.url);
   ctx.req.url = "/?filter[include]=vendors";
   console.log(ctx.req.url);
   console.log('GET api called');
   next();
});

this is changing the request url but not changing the response, it is the same and table is not included. I tried changing everything in req like

ctx.req.query = {filter: { include: 'vendors' }};

but no use. Any idea how can i achieve this. Both tables relation is already defined and I am able to get the desired result by making a custom api like,

expensecategories.expensecategory = function (cb) {
    expensecategories.find({
      include: {
        relation : 'vendors',
      }
    }, function(err, data) {
    cb(null, data);
    });
  };

  expensecategories.remoteMethod (
    'expensecategory', {
       description: 'get all expense types + vendors',
       http: {path: '/yes', verb: 'get'},
       returns: {arg: 'expensecategory', type: 'string'}
    }
  );

So, my table relation and everything is correct. I want the same result for /expensecategories also. Help!!!

3

3 Answers

0
votes

You can set the ExpenseCategory model default scope to include Vendor by adding a "scope" section:

"scope": {
    "include": "vendor"
  }
0
votes

One solution is to override the find remote path like this:

expensecategories.remoteMethod (
 'expensecategory', {
   description: 'get all expense types + vendors',
   http: {
     path: '/', // <-- HERE
     verb: 'get'
   },
   returns: {arg: 'expensecategory', type: 'string'}
  }
);

Update : this worked in previous Loopback versions, with current version you also have to do this, after expensecategories.setup() call :

expensecategories.disableRemoteMethod('find', true);

Update2 : this is how you should setup your Model :

// This is automatically called by loopback
MyModel.setup = function() {
  // Super setup
  MyModel.base.setup.apply(this, arguments);

 // Your customization
  MyModel.remoteMethod(...);
  MyModel.disableRemoteMethod(...);
};
0
votes

i know this question is answered, but I arrived here from Google with similar problem because i wanted to add another filter parameter on query for all requests.

Thing with relation did not work for me, so i continued to dig and found this snippet on access hooks in docs. So in the end i did this (based on your example):

expensecategories.observe('access', function (context, next) {
  context.query.where = context.query.where || {};
  context.query.where.include = 'vendors';
  next();
});