DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Data
  4. Design to Support New Query Parameters in GET Call Through Configurations Without Making Code Changes

Design to Support New Query Parameters in GET Call Through Configurations Without Making Code Changes

In this article, I’m discussing query parameters. Query parameter GET call is a set of parameters that are part of the URL.

Hemanth Atluri user avatar by
Hemanth Atluri
·
Dec. 02, 22 · Presentation
Like (1)
Save
Tweet
Share
10.23K Views

Join the DZone community and get the full member experience.

Join For Free

With this design support, new query parameters will be as easy as adding a new query parameter as a property in the application's configuration file. Implemented this using Spring Boot framework and MongoDB as the backend database. 

HTTP GET is two types of path parameters and query parameters. In this article, I’m discussing query parameters. Query parameter GET call is a set of parameters that are part of the URL. Query parameters are appended in the URL after the HTTP resource with ? symbol and multiple parameters are concatenated by & symbol. 

Implementation Details

The important part of this design is supporting the query parameters as they are referred to in the JSON path. With this, we can simply include the JSON path as the key and values in the Mongo Query. 

From below JSON example, forPerson resourceId for the JSON path is items.forPerson.resourceId. 

JSON
 
{
"_id": UUID('92f4b597-467a-4094-b796-27d1124c2fbd'),
"forName": {
   "firstName": "Hemanth",
   "lastName": "Atluri"
  },
"invoiceNumber": "387373872",
"items":[
  "resourceId": UUID('bad40e6b-4d17-433c-9c56-b61ea5bef06f'),
  "forPerson": {
    "resourceId": "9714a305-a9ec-4a3f-9ba6–93766b2c77b7"
  }
 ] 
}


In the implementation, all the query parameters provided are applied in AND fashion to filter the resources. 

Some of the query parameters have to be supported with exact values, greater than this value, less than this value, and this element exists. To support this, I used keywords from, to, after, before, and exists and added these to request parameters with a delimiter. 

Now let’s see the code to get a better understanding.

Let’s start with the Controller code: Controller class takes the help of RequestParamValidatorAndConvertor and MongoHelper to give a response back to the client. The core logic is in these two classes. Below is the code snippet:

Java
 
@RestController
@RequestMapping("/v1/orders")
public class MongoRestController {

    Logger log = LoggerFactory.getLogger(MongoRestController.class);

    @Autowired
    private RequestParamValidatorAndConvertor requestParamValidatorAndConvertor;

    @Autowired
    private MongoHelper mongoHelper;

    @GetMapping
    public ResponseEntity search(@RequestParam MultiValueMap<String, String> requestParams) {
        log.info(requestParams.toString());
        ResponseEntity responseEntity = null;
        try {
            List<QueryParameter> queryParameters = requestParamValidatorAndConvertor.validateAndConvertToQueryParameters(requestParams);
            List<Order> orders = mongoHelper.getOrders(queryParameters);
            responseEntity = ResponseEntity.status(HttpStatus.OK).body(orders);
        } catch (IllegalArgumentException ex) {
            responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body("UnSpported Query Parameter");
        }
        return responseEntity;
    }
}


RequestParamValidatorAndConvertor validates the provided query parameter and converts them into a List of CustomCriteria.Below is the code snippet: 

Java
 
public enum MongoOperator {
    IN, EXISTS, LT,LTE,GT,GTE;
}


Java
 
@NoArgsConstructor
@AllArgsConstructor
@Data
public class QueryParameter {
    private String attributeName;
    private String value;
    private MongoOperator mongoOperator;
}


Java
 
@Component
public class RequestParamValidatorAndConvertor {

    @Value("#{'${supportedQueryParamters}'.split(',')}")
    private List<String> supportedQueryParamters;

    public List<QueryParameter> validateAndConvertToQueryParameters(MultiValueMap<String, String> requestParams) {
        List<QueryParameter> queryParameters = new ArrayList<>();

        requestParams.forEach((key, value) -> {
            QueryParameter qp = new QueryParameter();
            if (key.contains(":")) {
                String[] keySplits = key.split(":");
                MongoOperator mongoOperator = null;

                String queryParameter = keySplits[0];
                String queryParamOperator = keySplits[1];

                if (!supportedQueryParamters.contains(queryParameter)) {
                    throw new IllegalArgumentException("Unsupported Query Parameter");
                }
                if (queryParamOperator.endsWith("from")) {
                    mongoOperator = MongoOperator.GTE;
                }
                if (queryParamOperator.endsWith("to")) {
                    mongoOperator = MongoOperator.LTE;
                }
                if (queryParamOperator.endsWith("after")) {
                    mongoOperator = MongoOperator.GT;
                }
                if (queryParamOperator.endsWith("before")) {
                    mongoOperator = MongoOperator.LT;
                }
                if (queryParamOperator.endsWith("exists")) {
                    mongoOperator = MongoOperator.EXISTS;
                }

                qp.setAttributeName(queryParameter);
                qp.setMongoOperator(mongoOperator);

            } else {
                if (!supportedQueryParamters.contains(key)) {
                    throw new IllegalArgumentException("Unsupported Query Parameter");
                }
                qp.setAttributeName(key);
                qp.setMongoOperator(MongoOperator.IN);
            }

            qp.setValue(String.valueOf(value));
            queryParameters.add(qp);
        });
        return queryParameters;
    }
}


MongoHelper class encapsulates the building of the criteria and querying the MongoDB. Below is the code snippet: 

Java
 
@Component
@AllArgsConstructor
public class MongoHelper {

    private MongoCriteriaBuilder mongoCriteriaBuilder;
    private MongoCustomRepository mongoCustomRepository;

    public List<Order> getOrders(List<QueryParameter> queryParameters) {
        Criteria criteria = mongoCriteriaBuilder.build(queryParameters);
        return mongoCustomRepository.findOrders(criteria);
    }
}


MongoCriteriaBuilder takes the QueryParameters for each query parameter; it creates Criteria and chains individual criteria with AND operator.

 
@Component
public class MongoCriteriaBuilder {

    public Criteria build(List<QueryParameter> queryParameters) {
        List<Criteria> criterias = new ArrayList<>();
        queryParameters.forEach(queryParameter -> {
            Criteria criteria = null;
            switch (queryParameter.getMongoOperator()) {
                case EXISTS:
                    criteria = Criteria.where(queryParameter.getAttributeName()).exists(Boolean.getBoolean(queryParameter.getValue()));
                case GT:
                    criteria = Criteria.where(queryParameter.getAttributeName()).gt(queryParameter.getValue());
                case GTE:
                    criteria = Criteria.where(queryParameter.getAttributeName()).gte(queryParameter.getValue());
                case LT:
                    criteria = Criteria.where(queryParameter.getAttributeName()).lt(queryParameter.getValue());
                case LTE:
                    criteria = Criteria.where(queryParameter.getAttributeName()).lte(queryParameter.getValue());
                default:
                    List<String> values = Arrays.stream(queryParameter.getValue().split(",")).collect(Collectors.toList());
                    criteria = Criteria.where(queryParameter.getAttributeName()).in(values);
            }
            criterias.add(criteria);
        });
        Criteria criteria = new Criteria().andOperator(criterias.toArray(new Criteria[criterias.size()]));
        return criteria;
    }
}


MongoCustomRepository build’s the mongo query with the criteria from the MongoCriteriaBuilder and passes it to the MongoTemplate to get the List of documents back. 

Java
 
@Component
@AllArgsConstructor
public class MongoCustomRepository {

    private MongoTemplate mongoTemplate;

    public List<Order> findOrders(Criteria criteria){
        Query query = new Query();
        query.addCriteria(criteria);
        return mongoTemplate.find(query, Order.class);
    }
}


Conclusion 

With the above implementation, new query parameters can be supported through configurations. This article shares only the talks about querying; this doesn’t include the performance of the query. To achieve performance in the query, one must index the field and understand MongoDB indexing.

Design Data Types Database Query language Spring Framework

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • API Design Patterns Review
  • 7 Awesome Libraries for Java Unit and Integration Testing
  • What Is a Kubernetes CI/CD Pipeline?
  • Deploying Java Serverless Functions as AWS Lambda

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: