Sunday 21 May 2017

How to search in a REST API express with multiple fields

I would like to perform a search request like https://api.mywebsite.com/users/search?firstname=jo&lastname=smit&date_of_birth=1980

I have a User schema like:

var UserSchema = new mongoose.Schema({
  role: { type: String, default: 'user' },
  firstname: { type: String, default: null },
  lastname: { type: String, default: null },
  date_of_birth: { type: Date, default: null, select: false },
});

What I did so far with stackoverflow help:

// check every element in the query and perform check function
function search_t(query) {
  return function (element) {
    for (var i in query) {
      if (query[i].function(element[i], query[i].value) == false) {
        return false;
      }
    }
    return true;
  }
}

// prepare query object, convert elements and add check function
// convert functions are used to convert string (from the query) in the right format
// check functions are used to check values from our users
function prepareSearch(query, cb) {
  let fields = {
    "firstname": {
      "type": "string",
      "function": checkString,
      "convert": convertString
    },
    "lastname": {
      "type": "string",
      "function": checkString,
      "convert": convertString
    },
    "date_of_birth": {
      "type": "date",
      "function": checkDate,
      "convert": convertDate
    }
  };
  for (let k in query) {
    k = k.toLowerCase();
    if (!(k in fields)) {
      return cb({message: "error"});
    }
    query[k] = {value: fields[k].convert(query[k]), function: fields[k].function};
  }
  return cb(null, query);
}

// linked to a route like router.get('/search/', controller.search);
export function search(req, res) {
  return User.find({}).exec()
    .then(users => {
      return prepareSearch(req.query, (err, query) => {
        if (err) {
          return handleError(res)(err);
        } else {
          return res.status(200).send(users.filter(search_t(query)));
        }
      });
    })
    .catch(handleError(res));
}

So this code works but I don't know if it's a good thing. I have a lot of other fields to check (like gender, ....) and I don't know if it's a good thing to do it "manually".

I don't know if mongoose has any function to do it. Should I use another method to filter / search in my users in my REST API ?

I'm pretty new here and I am not sure about how I work...

Thank you, Ankirama



via Ankirama

No comments:

Post a Comment