简体   繁体   中英

How to use param object instead of several params when there are too many optional parameters for a REST endpoint

I have a REST endpoint as shown below.

@Path("/api/observers")
public interface MyServiceEndpoint {

    @GET
    @Path("/history")
    HistoryPage<Action> getObserverHistory(@QueryParam("pageNum") @DefaultValue("1") int pageNum,
                                           @QueryParam("pageSize") @DefaultValue("25") int pageSize,
                                           @QueryParam("methodName") String methodName,
                                           @QueryParam("dateBefore") String dateBefore,
                                           @QueryParam("dateAfter") String dateAfter,
                                           @QueryParam("actionUUID") String actionUUID,
                                           @QueryParam("supersededByUUID") String supersededByUUID,
                                           @QueryParam("eventUUID") String eventUUID,
                                           @QueryParam("wasSuccessful") Boolean wasSuccessful);

}

As you can see, there are many params and some of them would be optional. I have been told that a better design pattern would be to use a param object instead of the specifying these several params. I am new to REST and I have no idea what this means and how to do it.
I also want to know once this is done, how to consume this from the AngularJS service ? Right now I am consuming this existing endpoint like :

myService.toggleEnabled = function (observer) {
            return $http({
                method: 'PUT',
                url: 'api/observers/history',
                headers: {
                    'Accept': mimeType,
                    'Content-Type': mimeType
                },
                params : {
                    pageNum: 1,
                    pageSize: 5
                }
            });
        };

Can someone give me an example for this or point me to the right direction / resources ?

Since JAX-RS 2.0, @BeanParam has been introduced as parameter aggregator. You just need to define simple POJO class with all your query parameters as fields:

public class ObserverHistoryParams {
    @QueryParam("pageNum") @DefaultValue("1") 
    private int pageNum;

    @QueryParam("pageSize") @DefaultValue("25") 
    private int pageSize;

    // other params & getters & setters
}

Then change getObserverHistory method signature to:

HistoryPage<Action> getObserverHistory(@BeanParam ObserverHistoryParams params) {
  ...
}

Using this approach, your Angular frontend interface doesn't need any change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM