Dawn17
Dawn17

Reputation: 8297

How to implement query string parameters for RESTful APIs

I am new to RESTful APIs and I've successfully implemented the GET and DELETE command for my API (GET localhost:4000/api, DELETE localhost:4000/api on Postman works fine).

Code for my get looks like:

router.get('/', function(req, res) {
    user.find({}, function(err, users) {
        if(err){
            res.status(404).send({
                message: err,
                data: []
            });
        } else {
            res.status(200).send({
                message: 'OK',
                data: users
            });
        }
    });
});

Now I want to implement using parameters. For example, I want to implement something like sorting where

http://localhost/4000/api/users?sort={"name": 1} (1- ascending; -1 - descending)

would mean sorting the name in ascending order.

What I am not sure how to do is:

  1. How do I make the ?sort thing work?

  2. How do I select which field to sort?

Please help!

Upvotes: 2

Views: 1876

Answers (2)

donquixote
donquixote

Reputation: 435

You can only pass order(asc, desc), if you want to sort by name you can do like that http://localhost/4000/api/users?order=-1 or http://localhost/4000/api/users?&order=1

then in your controller

router.get('/', function(req, res) {
  let order = req.query.order;
  user
   .find({})
   .sort({"name": order}) 
   .exec(function(err, users) {
      if(err){
          res.status(404).send({
              message: err,
              data: []
          });
      } else {
          res.status(200).send({
              message: 'OK',
              data: users
          });
      }
  });

});

These works if you use mongoose.js for mongodb

Upvotes: 2

Alexandru Olaru
Alexandru Olaru

Reputation: 7112

One cool solution that I frequently use is the following form

/api/users?sort=-name|+firstname

I use | for multiple fields sorting, and - for desc, + for asc

In express:

const { sort } = req.query; // sort = '-name|+firstname';
const order = sort.split('|') // will return an array ['-name', '+firstname']
 .reduce((order, item) => {
   const direction = item.charAt(0) === '-' ? -1 : 1;
   const field = item.substr(1);
   order[field] = direction;

   return order;
}, {})

// order {'name': -1, 'firstname': 1}

 users.find({}).sort(order); // do your logic

Upvotes: 1

Related Questions