| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package com.izouma.nineth.web;
- import cn.hutool.core.collection.CollUtil;
- import com.izouma.nineth.domain.News;
- import com.izouma.nineth.domain.NewsLike;
- import com.izouma.nineth.domain.User;
- import com.izouma.nineth.dto.PageQuery;
- import com.izouma.nineth.exception.BusinessException;
- import com.izouma.nineth.repo.NewsLikeRepo;
- import com.izouma.nineth.repo.NewsRepo;
- import com.izouma.nineth.service.CacheService;
- import com.izouma.nineth.service.NewsService;
- import com.izouma.nineth.utils.ObjUtils;
- import com.izouma.nineth.utils.SecurityUtils;
- import com.izouma.nineth.utils.excel.ExcelUtils;
- import lombok.AllArgsConstructor;
- import org.springframework.cache.annotation.Cacheable;
- import org.springframework.data.domain.Page;
- import org.springframework.security.access.prepost.PreAuthorize;
- import org.springframework.web.bind.annotation.*;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.util.List;
- @RestController
- @RequestMapping("/news")
- @AllArgsConstructor
- public class NewsController extends BaseController {
- private NewsService newsService;
- private NewsRepo newsRepo;
- private NewsLikeRepo newsLikeRepo;
- private CacheService cacheService;
- @PreAuthorize("hasAnyRole('ADMIN','NEWS')")
- @PostMapping("/save")
- public News save(@RequestBody News record) {
- if (record.getId() != null) {
- News orig = newsRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
- ObjUtils.merge(orig, record);
- orig = newsRepo.save(orig);
- cacheService.clearNews(record.getId());
- return orig;
- }
- record = newsRepo.save(record);
- cacheService.clearNews(record.getId());
- return record;
- }
- //@PreAuthorize("hasRole('ADMIN')")
- @PostMapping("/all")
- public Page<News> all(@RequestBody PageQuery pageQuery) {
- return newsService.all(pageQuery);
- }
- @GetMapping("/get/{id}")
- @Cacheable("news")
- public News get(@PathVariable Long id) {
- News news = newsRepo.findById(id).orElseThrow(new BusinessException("无记录"));
- User user = SecurityUtils.getAuthenticatedUser();
- if (user != null && !user.isAdmin()) {
- List<NewsLike> likes = newsLikeRepo.findByUserIdAndNewsId(user
- .getId(), id);
- news.setLiked(CollUtil.isNotEmpty(likes));
- }
- return news;
- }
- @PreAuthorize("hasAnyRole('ADMIN','NEWS')")
- @PostMapping("/del/{id}")
- public void del(@PathVariable Long id) {
- newsRepo.softDelete(id);
- cacheService.clearNews(id);
- }
- @GetMapping("/excel")
- @ResponseBody
- public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
- List<News> data = all(pageQuery).getContent();
- ExcelUtils.export(response, data);
- }
- }
|