ralixyle
ralixyle

Reputation: 785

How do I access a query string parameter in loopback model?

My api endpoint is like as follows for a model definition product.js

api/products/9720?id_shop=1&id_lang=1

I need to access the id_shop in product.js to apply a where clause before it fetches the records from products table.

Product.observe('access', function (ctx, next) {
    next();
});

How would I access id_shop and id_lang?

Upvotes: 5

Views: 4538

Answers (1)

amuramoto
amuramoto

Reputation: 2848

You can use a remote method to create a custom endpoint:

https://docs.strongloop.com/display/public/LB/Remote+methods

If you really want to alter the default behavior of Model.find(), you can use loopback.getCurrentContext() and then inject the filter for every GET request:

Product.on('dataSourceAttached', function(obj){
    var find = Product.find;
    Product.find = function(filter, cb) {           
        var id_shop = loopback.getCurrentContext().active.http.req.query.id_shop;           
        filter = {where:{id_shop: id_shop}};
        return find.apply(this, arguments);
    };
});

This would overwrite any filter passed in, so you would need to handle that with additional logic.

Upvotes: 4

Related Questions