Skip to content

Commit

Permalink
today 작업
Browse files Browse the repository at this point in the history
  • Loading branch information
seung-jun2 committed Aug 20, 2024
1 parent cbc7a4e commit 3c62ae3
Show file tree
Hide file tree
Showing 13 changed files with 365 additions and 46 deletions.
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ dependencies {
// implementation group: 'commons-io', name: 'commons-io', version: '2.9.0'
implementation 'com.google.guava:guava:33.1.0-jre'

//s3
implementation 'software.amazon.awssdk:s3:2.20.0'
implementation 'software.amazon.awssdk:sts:2.20.0'

}

tasks.named('test') {
Expand Down
18 changes: 18 additions & 0 deletions src/main/java/com/example/healthylife/config/S3Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.example.healthylife.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;

@Configuration
public class S3Config {
@Bean
public S3Client s3Client() {
return S3Client.builder()
.region(Region.AP_NORTHEAST_2) // 여러분의 AWS S3 리전으로 변경
.credentialsProvider(DefaultCredentialsProvider.create())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.example.healthylife.controller;

import com.example.healthylife.entity.TodayEntity;
import com.example.healthylife.entity.UserEntity;
import com.example.healthylife.service.HeartService;
import com.example.healthylife.service.TodayService;
import com.example.healthylife.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/hearts")
public class HeartController {

@Autowired
private HeartService heartService;

@Autowired
private UserService userService;

@Autowired
private TodayService todayService;

@ApiOperation("하트")
@PostMapping("/heart/{todaySq}")
public void like(@PathVariable("todaySq") long todaySq, @RequestParam String userId) {
Optional<UserEntity> user = userService.findUserById(userId);
Optional<TodayEntity> today = todayService.findbytodaysq(todaySq);

if (user.isPresent() && today.isPresent()) {
heartService.Like(user.get(), today.get());
} else {
// Handle the case when user or today entity is not found
throw new RuntimeException("User or Today entity not found");
}
}

@ApiOperation("하트 수")
@GetMapping("/count/{todaySq}")
public Long heartCount(@PathVariable("todaySq") long todaySq) {
Optional<TodayEntity> today = todayService.findbytodaysq(todaySq);
return heartService.HeartCount(today.orElse(null));
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
package com.example.healthylife.controller;

import com.example.healthylife.config.jwt.JwtUtil;
import com.example.healthylife.entity.CommunityEntity;
import com.example.healthylife.entity.TodayEntity;
import com.example.healthylife.entity.UserEntity;
import com.example.healthylife.repository.UserRepository;
import com.example.healthylife.service.TodayService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Optional;

@RequestMapping("/today")
@RestController
@RequiredArgsConstructor
public class TodayController {
private final TodayService todayService;
private final JwtUtil jwtUtil;
private final UserRepository userRepository;

@ApiOperation(value = "오운완 전체조회")
@GetMapping("/all")
Expand All @@ -24,28 +35,73 @@ public List<TodayEntity> todayList(){
//오운완 내가 쓴 글 조회
@ApiOperation(value = "오운완 내가쓴 글 조회")
@GetMapping("/myTodayContents")
public List<TodayEntity> myTodayContents(@RequestParam String userId){
return todayService.findMyTodayContents(userId);
public ResponseEntity<List<TodayEntity>> myTodayContents(@RequestHeader("Authorization") String authorizationHeader){
String jwtToken = jwtUtil.extractTokenFromHeader(authorizationHeader);
if (jwtToken == null || !jwtUtil.validateToken(jwtToken)) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
String userId = jwtUtil.getUserId(jwtToken);
List<TodayEntity> todayEntities = todayService.findMyTodayContents(userId);
if (todayEntities.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
return ResponseEntity.ok(todayEntities);
//확실하게 리스트에 담고싶으면 그래도됨
}

@ApiOperation(value = "오운완 글작성")
/* @ApiOperation(value = "오운완 글작성")
@PostMapping("/register")
public TodayEntity register (@RequestBody TodayEntity todayEntity){
return todayService.registerToday(todayEntity);
}
}*/

@ApiOperation(value = "오운완 글 수정")
@PutMapping("/update")
public ResponseEntity<TodayEntity> update(@RequestBody TodayEntity updatedTodayEntity, Authentication authentication) {
String username = authentication.getName(); // 인증된 사용자의 이름 (ID)

@ApiOperation(value = "오운완 글수정")
@PostMapping("/update")
public TodayEntity update(@RequestBody TodayEntity todayEntity){
return todayService.updateEntity(todayEntity);
try {
TodayEntity updatedEntity = todayService.updateEntity(updatedTodayEntity.getTodaySq(),updatedTodayEntity, username);
return ResponseEntity.ok(updatedEntity);
} catch (SecurityException e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); // 403 Forbidden 응답
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); // 404 Not Found 응답
}
}

@ApiOperation(value = "오운완 글삭제")
@PostMapping("/delete")
public Boolean delete(@RequestParam long todaySq){
@ApiOperation(value = "오운완 글 삭제")
@DeleteMapping("/delete/{todaySq}")
public ResponseEntity<Void> delete(@PathVariable("todaySq") Long todaySq, Authentication authentication) {
String username = authentication.getName(); // 인증된 사용자의 이름 (ID)
UserEntity user = userRepository.findByUserId(username)
.orElseThrow(() -> new RuntimeException("유저가 없습니다."));
// 권한 체크 또는 작성자 확인 로직 추가
todayService.deleteByTodaySq(todaySq);
return true;
return ResponseEntity.noContent().build();
}

@ApiOperation(value = "오운완 상세보기")
@GetMapping("/todayDetail/{todaysq}")
public ResponseEntity<TodayEntity> todaysq(@PathVariable("todaysq") Long todaysq) {
Optional<TodayEntity> todays = todayService.findTodayBySq(todaysq);
return todays.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).build());
}

@ApiOperation(value = "투데이 글 작성")
@PostMapping("/create")
public ResponseEntity<TodayEntity> createTodayPost(@RequestParam("content") String content,
@RequestPart("file") MultipartFile file,
Authentication authentication) {
String username = authentication.getName();
UserEntity user = userRepository.findByUserId(username)
.orElseThrow(() -> new RuntimeException("유저가 없습니다."));

// 투데이 글 작성
TodayEntity todayPost = todayService.createTodayPost(content, file, user);
return ResponseEntity.status(HttpStatus.CREATED).body(todayPost);
}


}
44 changes: 44 additions & 0 deletions src/main/java/com/example/healthylife/entity/HeartEntity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.example.healthylife.entity;

import lombok.*;

import javax.persistence.*;
import java.time.LocalDateTime;


@ToString
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "heart")
public class HeartEntity {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "heart_sq", unique = true, nullable = false)
private Long heartSq;

@ManyToOne
@JoinColumn(name = "user_sq", nullable = false)
private UserEntity user;

@ManyToOne
@JoinColumn(name = "today_sq", nullable = false)
private TodayEntity today;

@Column(name = "status", nullable = false)
private Boolean status;

@Column(name = "created_at", nullable = false)
private LocalDateTime createdAt = LocalDateTime.now();


// 상태를 토글하는 메서드
public void toggleStatus() {
this.status = !this.status;
}

}
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package com.example.healthylife.entity;

import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import com.fasterxml.jackson.annotation.JsonBackReference;
import lombok.*;

import javax.persistence.*;
import java.io.Serializable;
Expand All @@ -12,6 +10,7 @@
@ToString
@Entity
@Getter
@Setter
@Table(name = "today_comments")
@NoArgsConstructor
public class TodayCommentsEntity implements Serializable {
Expand All @@ -32,6 +31,7 @@ public class TodayCommentsEntity implements Serializable {
//게시글 넘버 시퀀스(foreign key)
@ManyToOne
@JoinColumn(name = "today_sq")
@JsonBackReference
private TodayEntity todayEntity;

//작성자
Expand All @@ -53,17 +53,4 @@ public TodayCommentsEntity(long todayCommentsSq, String todayCommentsContents, D
this.user = user;
}


//
//예시 데이터 여러개 넣기(반복으로 아무거나)
//테이블 만들기
//controller에 crud
//자유게시판 형식
//글제목,작성자,작성날짜,글내용,댓글
//글전체조회,키워드검색





}
18 changes: 12 additions & 6 deletions src/main/java/com/example/healthylife/entity/TodayEntity.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.example.healthylife.entity;

import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.*;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@ToString
@Entity
Expand All @@ -14,11 +16,6 @@
@NoArgsConstructor
public class TodayEntity implements Serializable {

//회원 아이디(유저 참조)
//오운완 시퀀스
//오운완 글제목
//오운완 글내용
//오운완 작성날짜

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Expand Down Expand Up @@ -47,16 +44,25 @@ public class TodayEntity implements Serializable {
@JoinColumn(name = "user_sq")
private UserEntity user;

//댓글
@JsonManagedReference
@OneToMany(mappedBy = "todayEntity", cascade = CascadeType.ALL, orphanRemoval = true)
private List<TodayCommentsEntity> comments;

@Column(name = "image_url")
private String imageurl;

// builder
@Builder(toBuilder = true)
public TodayEntity(long todaySq, String todayContents,
long todayHearts, Date todayCreated,
UserEntity user){
UserEntity user, String imageurl){
this.todaySq = todaySq;
this.todayContents = todayContents;
this.todayHearts = todayHearts;
this.todayCreated = todayCreated;
this.user = user;
this.imageurl = imageurl;
}


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.example.healthylife.repository;


import com.example.healthylife.entity.HeartEntity;
import com.example.healthylife.entity.TodayEntity;
import com.example.healthylife.entity.UserEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.Optional;

public interface HeartRepository extends JpaRepository<HeartEntity, Long> {
Optional<HeartEntity> findByUserAndToday(UserEntity user, TodayEntity todayentity);

@Query("SELECT COUNT(h) FROM HeartEntity h WHERE h.today = :today AND h.status = true")
Long HeartCount(@Param("today") TodayEntity today);
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ public interface TodayCommentsRepository extends JpaRepository<TodayCommentsEnti

//내가 작성한 글 조회하(유저아이디로)
List<TodayCommentsEntity> findByUserUserId(String userId);

List<TodayCommentsEntity> findByTodayEntity_todaySq(long todaySq);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface TodayRepository extends JpaRepository<TodayEntity, Long> {
// 오운완 내가 작성한 글 조회
// 오운완 내가 작성한 글 조회
List<TodayEntity> findByUserUserId(String userId);
//jpa 규칙 : findBy 라는 이름으로 시작해야 jpa 가 올바르게 쿼리를 생성
// 규칙에 맞지 않으면 메소드 생성 X 오류남

//today 시퀀스 단일 조화
Optional<TodayEntity> findByTodaySq(long todaySq);

Optional<TodayEntity> findByTodaySq(Long todaySq);
}
Loading

0 comments on commit 3c62ae3

Please sign in to comment.