cancel
Showing results for 
Search instead for 
Did you mean: 

SAP CAP Node JS - how to extract filter parameters?

MinhTriLe
Explorer
1,988

Hi,

For example, I have a CAP service request: /helloworld/Users?$filter=companyCode eq '123456'.

I have implemented a custom handler for Users entity - READ. 

I've been looking at Events and Requests | CAPire (cloud.sap) but I couldn't find any way to extract filter values. In this case, it is companyCode 123456

What is the correct way to extract filter values?

Regards,

Minh

Accepted Solutions (1)

Accepted Solutions (1)

RahulL
Discoverer

Hi @MinhTriLe,
You can fetch the filter results from filterValue = req.query.SELECT.where || {}; and use JSON.stringify(filterValue) to get those in readable format we will get the filterValue in ref and values format like below:

[{"ref":["companyCode"]},"=",{"val":"123456"}]
If we use the below code the desired output will be achieved:
function extractFilters(filters) {
    let result = {};
    for (let i = 0; i < filters.length; i++) {
        if (filters[i].ref) {
            // Extract the reference
            let ref = filters[i].ref[0];
            // Check if the next element is '=' and the element after that has a value
            if (filters[i + 1] === "=" && filters[i + 2] && filters[i + 2].val) {
                // Store the reference and its value
                result[ref] = filters[i + 2].val;
                // Skip the next two elements
                i += 2;
            }
        }
    }
    return result;
}

// Extracting the filters and their values
let filterValues = extractFilters(filters1);
console.log("Extracted filter values:", filterValues);
 
You'll get the output as Extracted filter values: { companyCode: '123456' }, now you can use the value for the business logic.

 

MinhTriLe
Explorer
0 Kudos
Hi RahulL, thanks for the hint. I'll try it.

Answers (2)

Answers (2)

Andrew_Mai
Participant

Usually, you will have to extract these kind of information from the req.query, for you case, it should be req.query.SELECT.where, then you can extract these information.

MinhTriLe
Explorer
0 Kudos
Hi Andrew_Mai, I'm able to get reg.query or req.query.SELECT.where. However, it's not in readable format. Do you know if SAP has any library to parse it into a readable format?
johnmurray
Participant

Possibly a bit late to help you, but hopefully to help others who come across this question - a url query parameters string is available at `req._.req.query` which I personally find a lot easier to deal with than the CSN version. As a side note `req._.req` is the unmodified request object from Express.