springspring-dataspring-data-rest

How to conditionally expose data in Spring Data REST projection?


There is a projection UserProjection and the User table has field - enable_email, a boolean.

@Projection(name = "summary", types = User.class)
public interface UserSummaryProjection {

    String getEmail();
}

Visiting URL /app/users/{id}?projection=summary shows the email as expected

  1. How can the summary projection be configured to return the email only if enable_email is true?

  2. Also will that configuration only affect this projection or be applicable across all projections for the User entity?


Solution

  • In projection, it was only a matter of annotating with @Value with Spring bean and method name as below:

    @Value("#{@userUtil.manageEmail(target)}")
    String getEmail();
    

    Then, I created a Spring Bean annotated with the @Component annotation and added the method below:

    public String manageEmail(User user) {
        Profile profile = profileRepo.findByUser(user);
        String[] paramsEnabled = profile.getSettings().split(",");
        boolean emailAllowed = Arrays.stream(paramsEnabled).anyMatch((s) -> (s.equals(Constants.EMAIL_ENABLED)));
    
        return  emailAllowed ? user.getEmail() : null;
    }