Wednesday 26 September 2018

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=10This 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.params.occupation) {queryObject = {...queryObject,occupation: req.params.occuption};}if (req.params.phoneVerified) {queryObject = {...queryObject,phoneVerified: req.params.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​

Submitted September 26, 2018 at 09:49AM by strawberrycandies

No comments:

Post a Comment