Adding a filter inside a remote key beforeRemote

I have a problem, I cannot find the answer in the Loopback docs.

Say I have a Company model and an Employee model. There is a 1Xn relationship between Company and its Employees . When /api/Employees is called, the server returns all employees.

I only want to return the list of employees who are in the same company with the user requesting the list.

To do this, I created a remote hook

  Employee.beforeRemote('find', function(context, modelInstance, next) { var reject = function() { process.nextTick(function() { next(null, false); }); }; // do not allow anonymous users var userId = context.req.accessToken.userId; if (!userId) { return reject(); } //I get the details of the user who sent the request //to learn which company does he belong to Employee.findById(userId, function(err, user) { if(!context.req.query.filter) context.req.query.filter={}; context.req.query.filter.where = {brandId:user.companyId}; console.log(context.req.query); next(); }); }); 

I thought this should work every time, but apparently it only works when there are already some query filters in the search, for example include, although console.log prints the correct context.req.query object.

What am I missing? Any help would be greatly appreciated!

+5
source share
1 answer

context.args.filter seems to work for this purpose. As a side note, instead of replacing where , you might want to combine it with something provided by the client. For an implementation idea, you can refer to: https://github.com/strongloop/loopback-datasource-juggler/blob/master/lib/utils.js#L56-L122

+9
source

Source: https://habr.com/ru/post/1216552/


All Articles