This commit is contained in:
2026-04-30 16:27:58 +08:00
parent ac6442a452
commit 2adefb5207
16 changed files with 284 additions and 349 deletions
@@ -1,20 +1,28 @@
package com.yaoyuan.jiscuss.dto;
import com.yaoyuan.jiscuss.entity.User;
import org.springframework.stereotype.Component;
import org.mapstruct.Mapper;
import org.mapstruct.MappingConstants;
import org.mapstruct.ReportingPolicy;
/**
* Manual mapper between {@link User} entity and DTO objects.
* MapStruct mapper between {@link User} entity and its DTOs.
*
* <p>Intentionally excludes the {@code password} field from all output DTOs.
* Replace with a generated MapStruct mapper if mapping complexity grows.
* <p>The {@code password} field is intentionally never copied into a response and
* is left {@code null} when constructing a {@link User} from a create request —
* the caller (service layer) is responsible for BCrypt-hashing and setting it.
*/
@Component
public class UserMapper {
@Mapper(
componentModel = MappingConstants.ComponentModel.SPRING,
unmappedTargetPolicy = ReportingPolicy.IGNORE
)
public interface UserMapper {
/** Map a {@link User} entity to a safe {@link UserResponse} (no password). */
public UserResponse toResponse(User user) {
if (user == null) return null;
default UserResponse toResponse(User user) {
if (user == null) {
return null;
}
return new UserResponse(
user.getId(),
user.getUsername(),
@@ -32,13 +40,15 @@ public class UserMapper {
);
}
/** Map a {@link UserCreateRequest} to a new {@link User} entity (password left unset — caller must hash it). */
public User fromCreateRequest(UserCreateRequest request) {
/** Map a create request to a new {@link User} entity. Password must be set by the caller. */
default User fromCreateRequest(UserCreateRequest request) {
if (request == null) {
return null;
}
User user = new User();
user.setUsername(request.username());
user.setEmail(request.email());
user.setRealname(request.realname());
// Caller is responsible for BCrypt-hashing the password before calling usersService.insert()
return user;
}
}