lightbringer
lightbringer

Reputation: 409

What is the best way to handle querystrings in an express api?

I am a beginner nodejs developer, working on developing an express rest api with optional query params.

For example consider the following schema for a user:

phone: {
  countryCode: String,
  number: phoneType
},
phoneVerified: { type: Boolean, default: false },
emailVerified: { type: Boolean, default: false },
rating: Number,
balance: { type: Number, default: 0 },
occupation: String,
gender: { type: String, enum: genders },

I want to expose this resource at /users and allow querying through optional query strings.

For ex, /users?emailVerified=true&phoneverified=false&gender=male&occupation=plumber&limit=10

This should return all the users which satisfy the criteria, while keeping almost all of the options optional.

What is the best way to do this in a maintenable and futureproof way?

Appraoch 1: My first approach was to use if blocks to check which parameters exist in the query and build mongoose queries accordingly, but that looks ugly and very hard to read.

queryObj = {};
if (req.query.occupation) {
  queryObject = {
    ...queryObject,
    occupation: req.query.occuption
  };
}
if (req.query.phoneVerified) {
  queryObject = {
    ...queryObject,
    phoneVerified: req.query.phoneVerifed
  };
}
const users = await User.find(queryObject);

I also found the querymen package which looks promising. If someone experinced could guide me as to what is the best practice? Thanks in advance

Upvotes: 0

Views: 158

Answers (1)

mehta-rohan
mehta-rohan

Reputation: 1341

you are doing it in right way. you can also try

queryObject = {};
if (req.query.params.occupation) {
    queryObject.occupation= req.params.occuption
}
if (req.params.phoneVerified) {
    queryObject.phoneVerified= req.params.phoneVerifed
}
const users = await User.find(queryObject);

you can add new properties to json using "."

Upvotes: 1

Related Questions