ArangoDB - Sort result in aql with custom function

Viewed 456

I'd like to have sorted result depending on user input.

Lets say I have sort object that could look like this:

var sort = {createdAt: -1}

or like this:

var sort = {createdAt: 1, name: 1}

And I have query that looks like this:

FOR f in [{createdAt: 123, name: 'BBB'},{createdAt: 2000, name: 'ZZZ'}, {createdAt: 2000, name: 'BBB'}]
    SORT f.createdAt DESC
    RETURN f

and it works ok. But I'd like to SORT result by field that is passed in sort object by user. I added custom arango function:

db.createFunction(
    'CUSTOM::FILTERING::SORT_STRING',
            String(function (sort, it) {
                    return sort && Object.keys(sort).length !== 0 && sort.constructor === Object ? Object.keys(sort).map(key => `${it}.${key} ${sort[key] >= 0 ? 'ASC' : 'DESC'}`).join(', ') : '';
            })
        );

but when I'm using it that way it doesn't work at all. Result is not sorted in any way:

FOR f in [{createdAt: 123, name: 'BBB'},{createdAt: 2000, name: 'ZZZ'}, {createdAt: 2000, name: 'BBB'}]
    SORT CUSTOM::FILTERING::SORT_STRING(${sort}, 'f')
    RETURN f

How can I sort result basing on different input arguments?

1 Answers
Related