Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loopbackjs

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?

like image 819
ralixyle Avatar asked Sep 25 '22 04:09

ralixyle


People also ask

What is parse request?

This is an action in the default HTTP sequence, it parses arguments from an incoming request and uses them as inputs to invoke the corresponding controller method.

What is repository in LoopBack?

A Repository represents a specialized Service interface that provides strong-typed data access (for example, CRUD) operations of a domain model against the underlying database or service. Note: Repositories are adding behavior to Models.

How do I create a service in LoopBack 4?

Components can contribute local services as follows. Run lb4 service and choose either Local service class or Local service provider as the service type to create. In your component constructor, create a service binding and add it to the list of bindings contributed by the component to the target application class.


1 Answers

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.

like image 84
amuramoto Avatar answered Sep 29 '22 02:09

amuramoto