marcosvidolin / copy-properties-assembler

A simple copy properties wrapper to convert domain into resource/dto and vice versa.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

copy-properties-assembler

Codacy Badge Build Status

A simple copy properties wrapper to convert domain into resource/dto and vice versa. Take a look at Ditiow.

Setup

Gragle

compile 'com.vidolima:copy-properties-assembler:v1.1.0'

Maven

<dependency>
	<groupId>com.vidolima</groupId>
	<artifactId>copy-properties-assembler</artifactId>
	<version>v1.1.0</version>
	<type>pom</type>
</dependency>

How to use

My entity class (usually)

@Entity
public class User {
  private String firstname;
  private String lastname;
  private String username;
  private String email;
  private String birthdate;
  // ...
}

User resource with some basics information that all users can see

public class BasicUserResource {
  private String firstname;
  private String username;
  // ...
}

User resource with full information. Only Admin can see

public class FullUserResource {
  private String firstname;
  private String lastname;
  private String username;
  private String email;
  private String birthdate;
  // ...
}

Assembler to convert the domain class (User) into a resource

public class UserAssembler extends GenericResourceAssembler<UserDomain> {
  public UserAssembler() {
    super(UserDomain.class);
  }
}

A rest controller exemplo that converts the User domain to a specific resource

@RestController
@RequestMapping(value = "/api/v1", produces = MediaType.APPLICATION_JSON_VALUE)
class UserController {
  
  private UserAssembler assembler = new UserAssember();

  /** Will return the basic user information. */
  @GetMapping(path = "/users/{username}")
  public ResponseEntity getBasicUser(@PathVariable String username) {
    User domain = this.service.findUserByUsername(username);
    BasicUserResource resource = this.assembler.fromDomain(domain, BasicUserResource.class);
    return ResponseEntity.ok(resource);
  }
  
  /** Will return all the user information (Admin only). */
  @GetMapping(path = "/admin/users/{username}")
  public ResponseEntity getBasicUser(@PathVariable String username) {
    User domain = this.service.findUserByUsername(username);
    FullUserResource resource = this.assembler.fromDomain(domain, FullUserResource.class);
    return ResponseEntity.ok(resource);
  }

}

Contributors

About

A simple copy properties wrapper to convert domain into resource/dto and vice versa.

License:MIT License


Languages

Language:Java 100.0%