cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

query options in function to database query

akuller
Participant
0 Kudos
450

Hello all,

I have defined a function that supports a filter. So far I access the filter parameters using req._queryOptions and build the select accordingly. My problem is that an additional requirement would now make this too complex.

function getNearbyPoints(latitude : Decimal, longitude : Decimal)  returns array of Records;

How can I pass the query options from the request directly into the query of the database?

I did find a topic on this here in SCN, but it is older and there was no answer.

Thanks a lot

Accepted Solutions (1)

Accepted Solutions (1)

martinstenzig
Contributor
0 Kudos

Try this (Full disclosure, this is not an officially supported interface):

const odata2cqn = require('@sap/cds/libx/odata/parser').parse

const o2c = odata2cqn(decodeURI(req.req.originalUrl))

That will parse your complete URL into a CQN and might have too much details, but you can strip out in the object what you don't need.

akuller
Participant

Hi martin.stenzig3

wow great, thank you very much. Too bad it's not a released function. The code is much nicer to read that way.

I have adapted your snippet a bit, I call the function in a batch request. Additionally I have defined a basic query and extend it with the requested options.

    this.on('getNearbyPoints', async (req) => {
try {
const p = new wkx.Point(req.data.longitude, req.data.latitude).toWkb()
var query = SELECT.distinct.from(...)
.columns...
.orderBy`distance ASC`
.where ...
.limit(50)
const functionURL = decodeURI(req._.odataReq._inRequestUrl),
odata2cqn = require('@sap/cds/libx/odata/parser').parse,
functionQuery = odata2cqn(functionURL)
functionQuery.SELECT.columns.forEach(element => {
const index = query.SELECT.columns.findIndex((obj) => (!!obj.ref && obj.ref[0] === element.ref[0]) || obj.as === element.ref[0]);
if (index === -1)
query.SELECT.columns.push(element)
})
query.SELECT.where.push('and')
query.SELECT.where = query.SELECT.where.concat(functionQuery.SELECT.where)
return await query
} catch (error) {
console.error(error.message)
}
})
julianSch
Associate
Associate
0 Kudos
Hello Martin,
julianSch
Associate
Associate
0 Kudos
Hello Martin, I need this exact same thing but for Java. Do you know if this exists ? Thank you

Answers (0)