-
Notifications
You must be signed in to change notification settings - Fork 0
/
[Chapter 10] 댓글 구현하기
682 lines (514 loc) · 18.8 KB
/
[Chapter 10] 댓글 구현하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
### 74. 댓글-Comment 모델 만들기
Comment 모델 만들기
Comment 레파지토리 만들기
Comment 서비스 만들기
Comment API 컨트롤러 만들기
댓글 쓰기
댓글 삭제
com.cos.photogramstart.domain.comment.Comment.java
```java
package com.cos.photogramstart.domain.comment;
import java.time.LocalDateTime;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import com.cos.photogramstart.domain.image.Image;
import com.cos.photogramstart.domain.likes.Likes;
import com.cos.photogramstart.domain.user.User;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder
@Entity // DB에 테이블을 생성
@Data
@NoArgsConstructor // 빈 생성자
@AllArgsConstructor // 전체 생성자
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // 번호 증가 전략이 데이터베이스를 따라간다.
private int id;
@Column(length=100,nullable=false)
private String content;
@JoinColumn(name="userId")
@ManyToOne(fetch=FetchType.EAGER)
private User user;
@JoinColumn(name="imageId")
@ManyToOne(fetch=FetchType.EAGER)
private Image image;
private LocalDateTime createDate;
@PrePersist // DB에 Insert가 되기 직전에 실행
public void createDate() {
this.createDate = LocalDateTime.now();
}
}
```
com.cos.photogramstart.domain.comment.CommentRepository.java
```java
package com.cos.photogramstart.domain.comment;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CommentRepository extends JpaRepository<Comment, Integer>{
}
```
### 75. 댓글-컨트롤러, 서비스 만들기
com.cos.photogramstart.service.CommentService.java
```java
package com.cos.photogramstart.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cos.photogramstart.domain.comment.Comment;
import com.cos.photogramstart.domain.comment.CommentRepository;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Service
public class CommentService {
private final CommentRepository commentRepository;
@Transactional
public Comment 댓글쓰기() {
return null;
}
@Transactional
public void 댓글삭제() {
}
}
```
com.cos.photogramstart.web.api.CommentApiController.java
```java
package com.cos.photogramstart.web.api;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cos.photogramstart.service.CommentService;
import lombok.RequiredArgsConstructor;
@RestController
@RequiredArgsConstructor
public class CommentApiController {
private final CommentService commentService;
@PostMapping("/api/comment")
public ResponseEntity<?> commentSave() {
return null;
}
@DeleteMapping("/api/comment/{id}")
public ResponseEntity<?> commentDelete(@PathVariable int id) {
return null;
}
}
```
### 76. 댓글-댓글쓰기 Ajax 함수 만들기
story.js
```java
// (4) 댓글쓰기
function addComment(imageId) {
let commentInput = $(`#storyCommentInput-${imageId}`);
let commentList = $(`#storyCommentList-${imageId}`);
let data = {
imagaId:imageId,
content: commentInput.val()
}
if (data.content === "") {
alert("댓글을 작성해주세요!");
return;
}
$.ajax({
type:"post",
url:"/api/comment",
data:JSON.stringify(data),
contentType:"application/json; charset=utf-8",
dataType:"json"
}).done(res=>{
console.log("성공",res);
}).fail(error=>{
console.log("오류",error);
})
let content = `
<div class="sl__item__contents__comment" id="storyCommentItem-2"">
<p>
<b>GilDong :</b>
댓글 샘플입니다.
</p>
<button><i class="fas fa-times"></i></button>
</div>
`;
commentList.prepend(content); // 최신 댓글
commentInput.val("");
}
```
### 77. 댓글-댓글쓰기 완료
CommitDto.java
```java
package com.cos.photogramstart.web.dto.comment;
import lombok.Data;
@Data
public class CommentDto {
private String content;
private int imageId;
// toEntity가 필요없음
}
```
CommentApiController.java
```java
package com.cos.photogramstart.web.api;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.cos.photogramstart.config.auth.PrincipalDatails;
import com.cos.photogramstart.domain.comment.Comment;
import com.cos.photogramstart.service.CommentService;
import com.cos.photogramstart.web.dto.CMRespDto;
import com.cos.photogramstart.web.dto.comment.CommentDto;
import lombok.RequiredArgsConstructor;
@RestController
@RequiredArgsConstructor
public class CommentApiController {
private final CommentService commentService;
@PostMapping("/api/comment")
public ResponseEntity<?> commentSave(@RequestBody CommentDto commentDto,
@AuthenticationPrincipal PrincipalDatails principalDatails ) { // x-www-~ 뭐시기 안받고 JSON 받으려면 @RequestBody 붙여야함
Comment comment = commentService.댓글쓰기(commentDto.getContent(),commentDto.getImageId(),principalDatails.getUser().getId()); // content, imageId, userId
return new ResponseEntity<>(new CMRespDto<>(1,"댓글쓰기성공",comment),HttpStatus.CREATED);
}
@DeleteMapping("/api/comment/{id}")
public ResponseEntity<?> commentDelete(@PathVariable int id) {
return null;
}
}
```
CommentService.java
```java
package com.cos.photogramstart.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cos.photogramstart.domain.comment.Comment;
import com.cos.photogramstart.domain.comment.CommentRepository;
import com.cos.photogramstart.domain.image.Image;
import com.cos.photogramstart.domain.user.User;
import com.cos.photogramstart.domain.user.UserRepository;
import com.cos.photogramstart.handler.ex.CustomApiException;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Service
public class CommentService {
private final CommentRepository commentRepository;
private final UserRepository userRepository;
@Transactional
public Comment 댓글쓰기(String content, int imageId, int userId) {
// Tip (객체를 만들 때 id값만 담아서 insert 할 수 있다.)
// 대신 return 시에 image객체와 user객체는 id값만 가지고 있는 빈 객체를 리턴받는다.
Image image = new Image();
image.setId(imageId);
User userEntity = userRepository.findById(userId).orElseThrow(()->{
throw new CustomApiException("유저 아이디를 찾을 수 없습니다.");
});
Comment comment = new Comment();
comment.setContent(content);
comment.setImage(image);
comment.setUser(userEntity);
return commentRepository.save(comment);
}
@Transactional
public void 댓글삭제() {
}
}
```
### 78. 댓글-뷰 렌더링
Comment.java
```java
@JoinColumn(name="imageId")
@ManyToOne(fetch=FetchType.EAGER)
private Image image;
```
story.js
```java
<div id="storyCommentList-${image.id}">`;
image.comments.forEach((comment)=>{
item += `<div class="sl__item__contents__comment" id="storyCommentItem-${comment.id}">
<p>
<b>${comment.user.username} :</b> ${comment.content}
</p>
<button>
<i class="fas fa-times"></i>
</button>
</div>`;
});
itme += `
$.ajax({
type:"post",
url:"/api/comment",
data:JSON.stringify(data),
contentType:"application/json; charset=utf-8",
dataType:"json"
}).done(res=>{
console.log("성공",res);
let comment = res.data;
let content = `
<div class="sl__item__contents__comment" id="storyCommentItem-${comment.id}">
<p>
<b>${comment.user.username}:</b>
${comment.content}
</p>
<button><i class="fas fa-times"></i></button>
</div>
`;
commentList.prepend(content); // 최신 댓글
}).fail(error=>{
console.log("오류",error);
})
commentInput.val(""); // 인풋 필드를 깨끗하게 비워준다.
```
ImageApiController.java
```java
@GetMapping("/api/image")
public ResponseEntity<?> imageStory(@AuthenticationPrincipal PrincipalDatails principalDatails,
@PageableDefault(size=3) Pageable pageable){
Page<Image> images = imageService.이미지스토리(principalDatails.getUser().getId(), pageable);
return new ResponseEntity<>(new CMRespDto<>(1, "성공",images),HttpStatus.OK); // JS에서 호출해야함
}
```
Image.java
```java
// 댓글
@OrderBy("id DESC")
@JsonIgnoreProperties({"image"})
@OneToMany(mappedBy = "image")
private List<Comment> comments;
```
### 79. 댓글-댓글 삭제하기
story.js
```java
// (0) 현재 로그인한 사용자 아이디
let principalId = $("#principalId").val();
// (5) 댓글 삭제
function deleteComment(commentId) {
$.ajax({
type:"delete",
url:`/api/comment/${commentId}`,
dataType:"json"
}).done(res=>{
console.log("성공",res);
$(`#storyCommentItem-${commentId`).remove();
}).fail(error=>{
console.log("성공",error);
});
}
```
CommentApiController.java
```java
package com.cos.photogramstart.web.api;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.cos.photogramstart.config.auth.PrincipalDatails;
import com.cos.photogramstart.domain.comment.Comment;
import com.cos.photogramstart.service.CommentService;
import com.cos.photogramstart.web.dto.CMRespDto;
import com.cos.photogramstart.web.dto.comment.CommentDto;
import lombok.RequiredArgsConstructor;
@RestController
@RequiredArgsConstructor
public class CommentApiController {
private final CommentService commentService;
@PostMapping("/api/comment")
public ResponseEntity<?> commentSave(@RequestBody CommentDto commentDto,
@AuthenticationPrincipal PrincipalDatails principalDatails ) { // x-www-~ 뭐시기 안받고 JSON 받으려면 @RequestBody 붙여야함
Comment comment = commentService.댓글쓰기(commentDto.getContent(),commentDto.getImageId(),principalDatails.getUser().getId()); // content, imageId, userId
return new ResponseEntity<>(new CMRespDto<>(1,"댓글쓰기성공",comment),HttpStatus.CREATED);
}
@DeleteMapping("/api/comment/{id}")
public ResponseEntity<?> commentDelete(@PathVariable int id) {
commentService.댓글삭제(id);
return new ResponseEntity<>(new CMRespDto<>(1,"댓글삭제성공",null),HttpStatus.OK);
}
}
```
CommentService.java
```java
@Transactional
public void 댓글삭제(int id) {
try {
commentRepository.deleteById(id);
} catch (Exception e) {
throw new CustomApiException(e.getMessage());
}
}
```
### 80. 댓글-유효성 검사하기
CommentDto.java
```java
package com.cos.photogramstart.web.dto.comment;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import lombok.Data;
// NotNull = Null값 체크
// NotEmpty = 빈 값이거나 null 체크
// NotBlank = 빈 값이거나 null 체크 그리고 빈 공백(스페이스)까지
@Data
public class CommentDto {
@NotBlank // 빈 값이거나 null 체크 그리고 빈 공백까지
private String content;
@NotNull // null 갑 체크
private Integer imageId;
// toEntity가 필요없음
}
```
CommentApiController.java
```java
package com.cos.photogramstart.web.api;
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.cos.photogramstart.config.auth.PrincipalDatails;
import com.cos.photogramstart.domain.comment.Comment;
import com.cos.photogramstart.handler.ex.CustomValidationApiException;
import com.cos.photogramstart.service.CommentService;
import com.cos.photogramstart.web.dto.CMRespDto;
import com.cos.photogramstart.web.dto.comment.CommentDto;
import lombok.RequiredArgsConstructor;
@RestController
@RequiredArgsConstructor
public class CommentApiController {
private final CommentService commentService;
@PostMapping("/api/comment")
public ResponseEntity<?> commentSave(@Valid @RequestBody CommentDto commentDto, BindingResult bindingResult,
@AuthenticationPrincipal PrincipalDatails principalDatails ) { // x-www-~ 뭐시기 안받고 JSON 받으려면 @RequestBody 붙여야함
if(bindingResult.hasErrors()) {
Map<String, String> errorMap = new HashMap<>();
for(FieldError error : bindingResult.getFieldErrors()) {
errorMap.put(error.getField(),error.getDefaultMessage());
// System.out.println(error.getDefaultMessage());
}
throw new CustomValidationApiException("유효성 검사 실패함", errorMap);
}
Comment comment = commentService.댓글쓰기(commentDto.getContent(),commentDto.getImageId(),principalDatails.getUser().getId()); // content, imageId, userId
return new ResponseEntity<>(new CMRespDto<>(1,"댓글쓰기성공",comment),HttpStatus.CREATED);
}
@DeleteMapping("/api/comment/{id}")
public ResponseEntity<?> commentDelete(@PathVariable int id) {
commentService.댓글삭제(id);
return new ResponseEntity<>(new CMRespDto<>(1,"댓글삭제성공",null),HttpStatus.OK);
}
}
```
UserApiController.java
```java
package com.cos.photogramstart.web.api;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.cos.photogramstart.config.auth.PrincipalDatails;
import com.cos.photogramstart.domain.user.User;
import com.cos.photogramstart.handler.ex.CustomValidationApiException;
import com.cos.photogramstart.handler.ex.CustomValidationException;
import com.cos.photogramstart.service.SubscribeService;
import com.cos.photogramstart.service.UserService;
import com.cos.photogramstart.web.dto.CMRespDto;
import com.cos.photogramstart.web.dto.subscribe.SubscribeDto;
import com.cos.photogramstart.web.dto.user.UserUpdateDto;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@RestController
public class UserApiController {
private final UserService userService;
private final SubscribeService subscribeService;
@PutMapping("/api/user/{principalId}/profileImageUrl")
public ResponseEntity<?> profileImageUrlUpdate(@PathVariable int principalId, MultipartFile profileImageFile, @AuthenticationPrincipal PrincipalDatails principalDatails) {
User userEntity = userService.회원프로필사진변경(principalId, profileImageFile);
principalDatails.setUser(userEntity); // 세션 변경
return new ResponseEntity<>(new CMRespDto<>(1, "프로필사진변경 성공",null), HttpStatus.OK);
}
@GetMapping("/api/user/{pageUserId}/subscribe")
public ResponseEntity<?> subscribeList(@PathVariable int pageUserId, @AuthenticationPrincipal PrincipalDatails principalDatails){
List<SubscribeDto> subscribeDto = subscribeService.구독리스트(principalDatails.getUser().getId(),pageUserId);
return new ResponseEntity<>(new CMRespDto<>(1,"구독자 정보 리스트 가져오기 성공",subscribeDto),HttpStatus.OK);
}
@PutMapping("/api/user/{id}")
public CMRespDto<?> update(
@PathVariable int id,
@Valid UserUpdateDto userUpdateDto,
BindingResult bindingResult, // 꼭 @Valid가 적혀 있는 다음 파라미터에 적어야함
@AuthenticationPrincipal PrincipalDatails principalDatails) {
if(bindingResult.hasErrors()) {
Map<String, String> errorMap = new HashMap<>();
for(FieldError error : bindingResult.getFieldErrors()) {
errorMap.put(error.getField(),error.getDefaultMessage());
// System.out.println(error.getDefaultMessage());
}
throw new CustomValidationApiException("유효성 검사 실패함", errorMap);
}else {
// System.out.println(userUpdateDto);
User userEntity = userService.회원수정(id, userUpdateDto.toEntity());
principalDatails.setUser(userEntity); // 세션 정보 변경(바뀌면 '남'이 뜨게 (gender))
return new CMRespDto<>(1,"회원수정완료",userEntity); // 응답시에 userEntity의 모든 getter 함수가 호출되고 JSON으로
// 파싱하여 응답한다.
}
}
}
```
story.js
```java
$.ajax({
type:"post",
url:"/api/comment",
data:JSON.stringify(data),
contentType:"application/json; charset=utf-8",
dataType:"json"
}).done(res=>{
console.log("성공",res);
let comment = res.data;
let content = `
<div class="sl__item__contents__comment" id="storyCommentItem-${comment.id}">
<p>
<b>${comment.user.username}:</b>
${comment.content}
</p>
<button onclick="deleteComment(${conment.id})"><i class="fas fa-times"></i></button>
</div>
`;
commentList.prepend(content); // 최신 댓글
}).fail(error=>{
console.log("오류",error.responseJson.data.content);
alert(error.responseJson.data.content);
})
commentInput.val(""); // 인풋 필드를 깨끗하게 비워준다.
```