userId나 userRole을 user-service에서 받아와야 하는 건가?
만약에 jwt 토큰으로 받아서 쓴다면 각 서비스에서 파싱을 해야하나?? 너무 비효율적 아닌가??
라고 고민하니까 초비님이 던져주심. @RequestHeader에 받아쓰거라...
JWT 토큰에 userId 포함시키기
기존 access 토큰에 userId를 그냥 포함시켜서 보내주면 굳이gateway에서 email을 보내줄 필요없이 userId를 보내주면 다른 서비스 모듈에서 FeignClient를 사용할 필요가 없다라는 생각이 들었다.기존 JWTUti
velog.io
1. 업체 생성
- 유저가 로그인을 함. 그럼 유저 정보를 어디서 받아오냐?
→ user-service에서 보내주냐, 게이트웨이에서 파싱해서 보내주냐? - 권한 - 유저 ROLE이 허브관리자거나 업체담당자일 때만 업체 생성 가능
- 업체 등록할 때는 companyHubId, companyManagerId까지 Request로 받는다고 가정함.
- companyHubId(업체 관리 허브ID) : 해당 허브가 존재하는지 체크
- companyManagerId(업체 담당자 ID) : 해당 유저가 존재하는지 체크
- 일단 다른 서비스에서 호출해서 주석 처리
- 질문 : 이렇게 되면 서비스 간 결합도가 너무 높지 않나? 다른 서비스에서 확인 받기 전에 업체 생성 못하는데?
- 답변 : 이 때 일단 먼저 업체 생성하되 서비스들에게 메세지로 너네 거 맞냐고 물어보고 아니라고 하면 그때 삭제하면 됨.
더보기
// 업체 생성
@Override
@Transactional
public CompanyResponseDto addCompany(CompanyRequestDto companyRequestDto, String userRole) {
// TODO 권한 - 유저 ROLE이 허브관리자 또는 업체담당자일 경우만 업체 생성 가능
// TODO 질문 - 만약 프론트엔드에서 이미 검증된 데이터를 보낸다면 굳이 필요없을 것 같음.
// TODO kafka를 이용해서 메세징 - 나 company 데이터 받았으니까 맞는지 확인해줘! 메세지 보내고 업체 생성하되 만약에 데이터가 안 맞는다는 메세지가 온다? 하면 바로 삭제
// companyHubId라는 허브가 존재하는지 확인
// boolean existedHubId = hubServiceClient.checkExistHubIdInHubList(companyCreateRequestDto.getCompanyHubId());
// if (!existedHubId) {
// throw new NotFoundException("해당 허브는 존재하지 않습니다.");
// }
// 허브 관리자의 경우, companyManagerId가 존재하는 유저 ID인지 확인
// boolean existedCompanyManagerId = userServiceClient.checkExistUserIdInUserList(companyCreateRequestDto.getCompanyManagerId());
// if ("HUB MANAGER".equalsIgnoreCase(userRole) && !existedCompanyManagerId){
// throw new NotFoundException("해당 업체 담당자ID는 존재하지 않습니다.");
// }
Company company = companyRepository.save(new Company(companyRequestDto));
return new CompanyResponseDto(company);
}
2. 개별 업체 조회
- docker포트 5432 이미 사용하고 있다고 해서 lsof 해도 안 나오더니 sudo로 하니까 보임…(허무)
- .env에 데이터베이스 URL, 이름, 비번 넣고 돌리니까 자꾸 못 찾음.
→ 루트 디렉토리에 .env 옮기니까 실행됨. 최상위 디렉토리에만 .env 만들 수 있는 건가? - 아니었음. 경로 copy path해서 넣어주니까 됐음ㅇㅇ
3. 업체 리스트 조회 + 검색
- .gitignore을 꼬박꼬박 넣도록 하자. 안 넣어다가 build/ 안 생겨서 Qclass 안 만들어짐.
- common 모듈에 QuerydslConfig를 만들었는데도 자꾸 JPAQueryFactory queryFactory < 빨간 줄 뜸.
- ComponentScan이 되지 않아서 그런 거였음.
@SpringBootApplication(scanBasePackages = {"com.fn.common"})
- 근데 그냥 주석 친 것처럼 entityManager 파라미터로 넣어서 해줘도 기능은 똑같음.
@Repository
public class CompanyQueryRepository {
private final JPAQueryFactory queryFactory;
// public CompanyQueryRepository(EntityManager entityManager) {
// this.queryFactory = new JPAQueryFactory(entityManager);
// }
@Autowired
public CompanyQueryRepository(JPAQueryFactory queryFactory) {
this.queryFactory = queryFactory;
}
public Page<CompanyResponseDto> findCompaniesByType(UUID hubId, String type, String keyword, Pageable pageable,
Sort.Direction sortDirection, PageUtils.CommonSortBy sortBy,
String userRole) {
QCompany company = QCompany.company;
BooleanBuilder builder = new BooleanBuilder();
// 삭제되지 않은 항목만 조회
builder.and(company.isDeleted.eq(false));
// 허브별 업체 조회 조건
if ("HUB MANAGER".equals(userRole) && "hub".equalsIgnoreCase(type) && hubId != null) {
builder.and(company.companyHubId.eq(hubId));
}
// 검색어 조건 (회사명 또는 주소)
if (keyword != null && !keyword.isEmpty()) {
builder.and(company.companyName.containsIgnoreCase(keyword)
.or(company.companyAddress.containsIgnoreCase(keyword)));
}
// 정렬 조건
OrderSpecifier<?> orderSpecifier = PageUtils.getCommonOrderSpecifier(company, sortDirection, sortBy);
// QueryDSL 조회
JPAQuery<Company> query = queryFactory
.selectFrom(company)
.where(builder)
.orderBy(orderSpecifier)
.offset(pageable.getOffset())
.limit(pageable.getPageSize());
List<Company> result = query.fetch();
long total = query.fetchCount();
// 엔티티 → DTO 변환
List<CompanyResponseDto> dtoList = result.stream()
.map(CompanyResponseDto::new)
.collect(Collectors.toList());
return new PageImpl<>(dtoList, pageable, total);
}
}
4. 업체 수정/삭제
- 자꾸 JpaAuditingHandler 에러가 나서 당연히 도메인에 .env 넣어서 그렇구나ㅜ 했는데
common에서 이미 @EnableJpaAuditing을 해주니까 CompanyApplication에서 한 번 더 할 필요는 없었던 거였음.
하, 나 상품이랑 주문, AI도 만들어야 하는데 왜 자꾸 고난이... 깃 ...이 개잣식...
728x90
'TIL' 카테고리의 다른 글
TIL26. 상품 만들기 (2) - 수정, 삭제 + Git Conflict, 401 Error (0) | 2025.03.19 |
---|---|
TIL25. 상품 만들기 (1) 생성, 조회 (0) | 2025.03.18 |
TIL23. 공통 모듈 만들기 - Exception, BaseEntity (0) | 2025.03.14 |
TIL22. SAGA Pattern + JMeter (0) | 2025.03.13 |
TIL21. 물류 관리 및 배송 시스템 프로젝트 시작!! (0) | 2025.03.12 |