NewsController.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package com.izouma.nineth.web;
  2. import cn.hutool.core.collection.CollUtil;
  3. import com.izouma.nineth.domain.News;
  4. import com.izouma.nineth.domain.NewsLike;
  5. import com.izouma.nineth.domain.User;
  6. import com.izouma.nineth.repo.NewsLikeRepo;
  7. import com.izouma.nineth.service.NewsService;
  8. import com.izouma.nineth.dto.PageQuery;
  9. import com.izouma.nineth.exception.BusinessException;
  10. import com.izouma.nineth.repo.NewsRepo;
  11. import com.izouma.nineth.utils.ObjUtils;
  12. import com.izouma.nineth.utils.SecurityUtils;
  13. import com.izouma.nineth.utils.excel.ExcelUtils;
  14. import lombok.AllArgsConstructor;
  15. import org.springframework.cache.annotation.Cacheable;
  16. import org.springframework.data.domain.Page;
  17. import org.springframework.security.access.prepost.PreAuthorize;
  18. import org.springframework.web.bind.annotation.*;
  19. import javax.servlet.http.HttpServletResponse;
  20. import java.io.IOException;
  21. import java.util.List;
  22. @RestController
  23. @RequestMapping("/news")
  24. @AllArgsConstructor
  25. public class NewsController extends BaseController {
  26. private NewsService newsService;
  27. private NewsRepo newsRepo;
  28. private NewsLikeRepo newsLikeRepo;
  29. @PreAuthorize("hasAnyRole('ADMIN','NEWS')")
  30. @PostMapping("/save")
  31. public News save(@RequestBody News record) {
  32. if (record.getId() != null) {
  33. News orig = newsRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
  34. ObjUtils.merge(orig, record);
  35. return newsRepo.save(orig);
  36. }
  37. return newsRepo.save(record);
  38. }
  39. //@PreAuthorize("hasRole('ADMIN')")
  40. @PostMapping("/all")
  41. public Page<News> all(@RequestBody PageQuery pageQuery) {
  42. return newsService.all(pageQuery);
  43. }
  44. @GetMapping("/get/{id}")
  45. @Cacheable("news")
  46. public News get(@PathVariable Long id) {
  47. News news = newsRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  48. User user = SecurityUtils.getAuthenticatedUser();
  49. if (user != null && !user.isAdmin()) {
  50. List<NewsLike> likes = newsLikeRepo.findByUserIdAndNewsId(user
  51. .getId(), id);
  52. news.setLiked(CollUtil.isNotEmpty(likes));
  53. }
  54. return news;
  55. }
  56. @PreAuthorize("hasAnyRole('ADMIN','NEWS')")
  57. @PostMapping("/del/{id}")
  58. public void del(@PathVariable Long id) {
  59. newsRepo.softDelete(id);
  60. }
  61. @GetMapping("/excel")
  62. @ResponseBody
  63. public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
  64. List<News> data = all(pageQuery).getContent();
  65. ExcelUtils.export(response, data);
  66. }
  67. }