keithwhor / nodal

API Services Made Easy With Node.js

Home Page:http://www.nodaljs.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

orderBy Query Parameter

edgar971 opened this issue · comments

Hi,

I was searching through the documentation and example tutorials and I couldn't figure out how to use sortBy with query parameters. I want to be able to make API calls like http://localhost:8080/v1/sites?__orderBy=created_at,DESC to have a custom sort. Is there a way to do this natively with Nodal? I also tried the following versions:

http://localhost:8080/v1/sites?__orderBy=created_at|DESC
http://localhost:8080/v1/sites?orderBy=created_at,DESC
http://localhost:8080/v1/sites?orderBy=created_at|DESC

The controller looks like this:

Site.query()
            .where(this.params.query)
            .end((err, models) => {


                this.respond(err || models);

            });

Thanks!

By Query composer you have the .orderBy() method, something like...

...
Customer.query()
   .where(this.params.query)
    .join('phones')
    .limit(this.params.query.offset, process.env.QUERY_LIMIT)
    .orderBy("id", "DESC") // here you put your params
    .end((err, cliente) => {
...

Just send the values what you want in body or, like you said, in you query string.

You have another options, see http://nsipplswezey.github.io/nodal/docs/graphql.html

@nogsantos Thanks for the help.

I ended up doing the following:

Created a function to parse the orderBy query.

parseOrderBy(query) {

        let orderBy = [];

        if (!query.__orderBy && query.__orderBy.length) return false;

        orderBy = query.__orderBy.split('|');

        return orderBy;

    }

Used the function inside my index method.

let order = this.parseOrderBy(this.params.query);
        console.log(order);

        Site.query()
            .where(this.params.query)
            .orderBy(...order)
            .end((err, models) => {


                this.respond(err || models);

            });

That worked for me.

@edgar971 you should use __order instead of __orderBy param in your HTTP request. So in your case it will be looks like http:///localhost:8080/v1/sites?__order=created_at desc.