0

I am building a REST API with Dropwizard and JDBI and I need to work with different representations of the same resource.

An example where we are working with a events resource:

A event resource has properties field1, field2, field3 and field4.

  1. When creating a new event by doing POST /events the request body should contain all properties.
  2. When fetching an event by doing GET /event/1 as a normal user the response body should only contain field1 and field2.
  3. When fetching an event by doing GET /event/1 as a super user the response body should contain field1, field2 and field3.

What is the best (simple) way of dealing with this (#2 and #3) when it comes to the resource bean, the jdbi query and the resource mapper?

Separate bean/mapper/query for each representation (not very DRY, even with a base bean that is extended)? Filtering the response object after it's been built (not very elegant and possibly brittle, easy to accidentally expose too much data)?

Samuel Lindblom
  • 812
  • 1
  • 6
  • 22

1 Answers1

1

Separate mapper/query is not needed for this case. We should always use DTO(Data transfer objects) for response, when there is difference between business model and response. Lets say, you have business model like,

public class Event {
  private String field1;
  private String field2;
  private String field3;
  private String field4;
}

Use this model for creating events. For fetching event, there should be two DTOs.

public class NormalUserEventDto implements IEventDto{
  private String field1;
  private String field2;
}

public class SuperUserEvent implements IEventDto {
  private String field1;
  private String field2;
  private String field3;
}

Query to bean mapper still can give Event model. Depending upon the user, you can give DTO. There are some libraries available to convert one bean to another bean. You can use that also or you can write the logic to convert also.

Manikandan
  • 3,025
  • 2
  • 19
  • 28