黑马头条项目[修改版]-第五天

时间:2024-03-09 15:44:02

0.黑马头条-学习目标

  • 完成自媒体文章列表查询功能
  • 完成自媒体文章的发布功能
  • 完成自媒体文章的查询
  • 完成自媒体文章的删除功能
  • 完成自媒体文章的上下架功能功能

1.自媒体文章列表查询

1.1.需求分析

1604150560484

1.2.表结构和实体类

leadnews_wemedia数据库:自媒体文章表:wm_news

1604150801492

在heima-leadnews-model中创建WmNews实体类

/**
 * <p>
 * 自媒体图文内容信息表
 * </p>
 *
 * @author itheima
 */
@Data
@TableName("wm_news")
public class WmNews implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * 自媒体用户ID
     */
    @TableField("user_id")
    private Integer userId;

    /**
     * 标题
     */
    @TableField("title")
    private String title;

    /**
     * 图文内容
     */
    @TableField("content")
    private String content;

    /**
     * 文章布局
            0 无图文章
            1 单图文章
            3 多图文章
     */
    @TableField("type")
    private Short type;

    /**
     * 图文频道ID
     */
    @TableField("channel_id")
    private Integer channelId;

    @TableField("labels")
    private String labels;

    /**
     * 创建时间
     */
    @TableField("created_time")
    private Date createdTime;

    /**
     * 提交时间
     */
    @TableField("submited_time")
    private Date submitedTime;

    /**
     * 当前状态
            0 草稿
            1 提交(待审核)
            2 审核失败
            3 人工审核
            4 人工审核通过
            8 审核通过(待发布)
            9 已发布
     */
    @TableField("status")
    private Short status;

    /**
     * 定时发布时间,不定时则为空
     */
    @TableField("publish_time")
    private Date publishTime;

    /**
     * 拒绝理由
     */
    @TableField("reason")
    private String reason;

    /**
     * 发布库文章ID
     */
    @TableField("article_id")
    private Integer articleId;

    /**
     * //图片用逗号分隔
     */
    @TableField("images")
    private String images;

    @TableField("enable")
    private Short enable;
    
     //状态枚举类
    @Alias("WmNewsStatus")
    public enum Status{
        NORMAL((short)0),SUBMIT((short)1),FAIL((short)2),ADMIN_AUTH((short)3),ADMIN_SUCCESS((short)4),SUCCESS((short)8),PUBLISHED((short)9);
        short code;
        Status(short code){
            this.code = code;
        }
        public short getCode(){
            return this.code;
        }
    }

}

1.3.接口定义

1.在heima-leadnews-apis中创建接口:com.heima.api.wemedia.WmNewsControllerApi

public interface WmNewsControllerApi {

    /**
     * 分页带条件查询自媒体文章列表
     * @param dto
     * @return
     */
    public ResponseResult findAll(WmNewsPageReqDto dto);
}

2.在heima-leadnews-model中创建:com.heima.model.wemedia.dtos.WmNewsPageReqDto

@Data
public class WmNewsPageReqDto extends PageRequestDto {

    /**
     * 状态
     */
    private Short status;
    /**
     * 关键字
     */
    private String keyword;

    /**
     * 频道
     */
    private Integer channelId;

    /**
     * 开始时间
     */
    private Date beginPubDate;

    /**
     * 结束时间
     */
    private Date endPubDate;
}

1.4.功能实现

1.在heima-leadnews-wemedia中创建mapper接口:com.heima.wemedia.mapper.WmNewsMapper

@Mapper
public interface WmNewsMapper extends BaseMapper<WmNews> {
}

2.在heima-leadnews-wemedia中创建service接口:com.heima.wemedia.service.WmNewsService

public interface WmNewsService extends IService<WmNews> {

    /**
     * 分页带条件查询自媒体文章列表
     * @param dto
     * @return
     */
    public ResponseResult findAll(WmNewsPageReqDto dto);
}

3.在heima-leadnews-wemedia中创建service接口实现类:com.heima.wemedia.service.impl.WmNewsServiceImpl

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //2.分页条件查询
        IPage pageParam = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //状态精确查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道精确查询
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //根据自媒人精确查询
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());

        //按照发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getPublishTime);
        IPage pageResult = page(pageParam, lambdaQueryWrapper);

        //3.结果封装返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        responseResult.setData(pageResult.getRecords());
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }
}

4.在heima-leadnews-wemedia中创建controller:com.heima.wemedia.controller.v1.WmNewsController

@RestController
@RequestMapping("/api/v1/news")
public class WmNewsController implements WmNewsControllerApi {

    @Autowired
    private WmNewsService wmNewsService;

    @PostMapping("/list")
    @Override
    public ResponseResult findAll(@RequestBody WmNewsPageReqDto dto) {
        return wmNewsService.findAll(dto);
    }
}

1.5.测试

导入资料中的前端项目project-heima-leadnews-wemedia-vue-master,并启动

启动后端项目

  • heima-leadnews-wemedia-gateway
  • heima-leadnews-wemedia
  • heima-leadnews-admin-gateway
  • heima-leadnews-admin
  • nacos
  • seata

之后浏览器输入地址:localhost:8080,访问测试。

2.频道列表加载

2.1.需求分析

1604154393010

文章展示列表页面打开的时候,默认自动加载频道列表数据进行展示,就是查询所有频道数据

2.2.接口定义

1.在heima-leadnews-apis中的AdChannelControllerApi新增方法

/**
     * 查询所有频道
     * @return
     */
    public ResponseResult findAll();

2.在heima-leadnews-admin中的AdChannelController中实现方法

@GetMapping("/channels")
@Override
public ResponseResult findAll() {
        List<AdChannel> list = adChannelService.list();
        return ResponseResult.okResult(list);
}

3.在heima-leadnews-wemedia-gateway的application.yml中增加配置

spring:
  application:
    name: leadnews-wemedia-gateway
  cloud:
    nacos:
    
     ......
     
    gateway:
      globalcors:
      
        ......
        
      routes:
      
      .....

      - id: admin
        uri: lb://leadnews-admin
        predicates:
        - Path=/admin/**
        filters:
        - StripPrefix= 1

4.重新启动项目,重新测试

3.自媒体文章-发布修改保存草稿

3.1.需求分析

1604238970500

leadnews_wemedia数据库

自媒体文章表:wm_news

1604150801492

素材表:wm_material

1604239355856

文章素材关系表:wm_news_material

1604239365731

3.2.接口定义

思路分析

  • 该功能为保存、修改(是否有id)、保存草稿的共有方法
  • 如果有id修改文章,先删除所有素材关联关系
  • 如果没有id,保存文章
  • 关联内容中的图片与素材的关系
  • 关联封面中的图片与素材的关系
  • 封面图片如果选择是自动需要从内容中截图图片做为封面图片
    • 截取规则为:内容图片的个数小于等于2 则为单图截图一张图,内容图片大于等于3,则为多图,截图三张图,内容中没有图片,则为无图

前端传递给后端的参数

{
    "title":"黑马头条项目背景",
    "type":"1",//这个 0 是无图  1 是单图  3 是多图  -1 是自动
    "labels":"黑马头条",
    "publishTime":"2020-03-14T11:35:49.000Z",
    "channelId":1,
    "images":[
        "http://192.168.200.130/group1/M00/00/00/wKjIgl5swbGATaSAAAEPfZfx6Iw790.png"
    ],
    "status":1,
    "content":"[
    {
        "type":"text",
        "value":"随着智能手机的普及,人们更加习惯于通过手机来看新闻。由于生活节奏的加快,很多人只能利用碎片时间来获取信息,因此,对于移动资讯客户端的需求也越来越高。黑马头条项目正是在这样背景下开发出来。黑马头条项目采用当下火热的微服务+大数据技术架构实现。本项目主要着手于获取最新最热新闻资讯,通过大数据分析用户喜好精确推送咨询新闻"
    },
    {
        "type":"image",
        "value":"http://192.168.200.130/group1/M00/00/00/wKjIgl5swbGATaSAAAEPfZfx6Iw790.png"
    }
  ]"
}

接口定义

1.在heima-leadnews-apis中的WmNewsControllerApi中新增接口方法

public interface WmNewsControllerApi {

    ....

    /**
     * 保存、修改文章,保存草稿
     * @return
     */
    public ResponseResult submitNews(WmNewsDto dto);
}

2.在heima-leadnews-model中创建WmNewsDto

@Data
public class WmNewsDto {

    private Integer id;
    /**
     * 标题
     */
    private String title;
    /**
     * 频道id
     */
    private Integer channelId;
    /**
     * 标签
     */
    private String labels;
    /**
     * 发布时间
     */
    private Date publishTime;
    /**
     * 文章内容
     */
    private String content;
    /**
     * 文章封面类型  0 无图 1 单图 3 多图 -1 自动
     */
    private Short type;
    /**
     * 是否上架  0 下架  1 上架
     */
    private Short enable;
    /**
     * 提交时间
     */
    private Date submitedTime;
    /**
     * 状态 提交为1  草稿为0
     */
    private Short status;
    /**
     * 拒绝理由
     */
    private String reason;
    /**
     * 封面图片列表 多张图以逗号隔开
     */
    private List<String> images;

}

3.3.业务层实现1

1.在heima-leadnews-wemedia中的WmNewsController实现方法

@RestController
@RequestMapping("/api/v1/news")
public class WmNewsController implements WmNewsControllerApi {

    @Autowired
    private WmNewsService wmNewsService;

    .......

    
    @Override
    public ResponseResult submitNews(@RequestBody WmNewsDto dto) {
       return null;
    } 
}

2.在heima-leadnews-wemedia中的WmNewsService新增接口方法

public interface WmNewsService extends IService<WmNews> {

    ........

    /**
     * 自媒体文章发布
     * @param dto
     * @param isSubmit 是否为提交  1 提交  0 草稿
     * @return
     */
    public ResponseResult saveNews(WmNewsDto dto,Short isSubmit);
    
}

3.在heima-leadnews-wemedia中的WmNewsServiceImpl实现方法

/**
 * 自媒体文章发布
 * @param dto
 * @param isSubmit 是否为提交  1 提交  0 草稿
 * @return
 */
@Override
public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.保存或修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        if (WemediaContans.WM_NEWS_AUTO_TYPE.equals(dto.getType())) {
            wmNews.setType(null);
        }
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //[dfjksdjfdfj.jpg,sdlkjfskld.jpg]
            wmNews.setImages(dto.getImages().toString().replace("[", "")
                    .replace("]", "").replace(fileServerUrl, "")
                    .replace(" ", ""));
        }
        //保存或修改文章
        saveWmNews(wmNews, isSubmit);


        return null;
}


@Autowired
private WmNewsMaterialMapper wmNewsMaterialMapper;

/**
 * 保存或修改文章
 *
 * @param wmNews
 * @param isSubmit
*/
private void saveWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setStatus(isSubmit);
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        if (wmNews.getId() == null) {
            save(wmNews);
        } else {
            //如果是修改,则先删除素材与文章的关系
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
            updateById(wmNews);
        }
}


4.在heima-leadnews-common中的WemediaContans中增加常量

public class WemediaContans {

    public static final Short COLLECT_MATERIAL = 1;//收藏

    public static final Short CANCEL_COLLECT_MATERIAL = 0;//收藏

    public static final Short WM_NEWS_SINGLE_TYPE = 1;
    public static final Short WM_NEWS_NONE_TYPE = 0;
    public static final Short WM_NEWS_MANY_TYPE = 3;
    public static final Short WM_NEWS_AUTO_TYPE = -1;

    public static final String WM_NEWS_TYPE_IMAGE = "image";

    public static final Short WM_NEWS_CONTENT_REFERENCE =0;
    public static final Short WM_NEWS_COVER_REFERENCE =1;

    public static final Short WM_NEWS_ENABLE_UP =1;


}

3.4.业务层实现2

 /**
     * 自媒体文章发布
     * @param dto
     * @param isSubmit 是否为提交  1 提交  0 草稿
     * @return
     */
    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
       
       .....


        //3.关联文章与素材的关系
        String content = dto.getContent();
        List<Map> list = JSON.parseArray(content, Map.class);
        List<String> materials = ectractUrlInfo(list);

        .......


        return null;
    }



/**
     * 提取图片信息
     *
     * @param list
     * @return
     */
    private List<String> ectractUrlInfo(List<Map> list) {
        List<String> materials = new ArrayList<>();
        for (Map map : list) {
            if (map.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
                String imgUrl = (String) map.get("value");
                imgUrl = imgUrl.replace(fileServerUrl, "");
                materials.add(imgUrl);
            }
        }
        return materials;
    }

3.5.业务层实现3

/**
     * 自媒体文章发布
     * @param dto
     * @param isSubmit 是否为提交  1 提交  0 草稿
     * @return
     */
    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        
        
        ......

        //3.1 关联内容中的图片与素材的关系
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && materials.size() != 0) {
            ResponseResult responseResult = saveRelativeInfoForContent(materials, wmNews.getId());
            if (responseResult != null) {
                return responseResult;
            }
        }

        
        ......


        return null;
    }





/**
     * 保存素材与文章内容的关系
     *
     * @param materials
     * @param newsId
     * @return
     */
    private ResponseResult saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        return saveRelativeInfo(materials, newsId, WemediaContans.WM_NEWS_CONTENT_REFERENCE);
    }




@Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 保存关系
     *
     * @param materials
     * @param newsId
     * @param type
     * @return
     */
    private ResponseResult saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        //1.获取数据库中的素材信息
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl, materials);
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId());
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(lambdaQueryWrapper);
        //2.通过图片的路径获取素材的id
        List<String> materialsIds = new ArrayList<>();
        if (dbMaterials != null && dbMaterials.size() > 0) {
            //<kdjfksdjkfljdsf.jps,2>
            Map<String, Integer> uriIdMap = dbMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
            for (String val : materials) {
                String materialId = String.valueOf(uriIdMap.get(val));
                //没找到
                if ("null".equals(materialId)) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "应用图片失效");
                }
                //找到了
                materialsIds.add(materialId);
            }
        }

        //3.批量保存数据
        wmNewsMaterialMapper.saveRelations(materialsIds, newsId, type);
        return null;
}

在WmNewsMaterialMapper中自定义方法

@Mapper
public interface WmNewsMaterialMapper extends BaseMapper<WmNewsMaterial> {

    void saveRelations(@Param("materials") List<String> materialsIds, @Param("newsId")Integer newsId, @Param("type")Short type);
}

创建WmNewsMaterialMapper.xml映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.heima.wemedia.mapper.WmNewsMaterialMapper">
    <insert id="saveRelations">
        insert into wm_news_material (material_id, news_id, type, ord)
        values
        <foreach item="mid" index="ord" collection="materials"  separator="," >
            (#{mid}, #{newsId}, #{type}, #{ord})
        </foreach>
    </insert>
</mapper>

3.6.业务实现4

/**
 * 自媒体文章发布
 * @param dto
 * @param isSubmit 是否为提交  1 提交  0 草稿
 * @return
 */
@Override
public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
    
    .......

    //3.2 关联封面中的图片与素材的关系,设置wm_news的type,自动
    if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
        ResponseResult responseResult = saveRelativeInfoForCover(dto, materials, wmNews);
        if (responseResult != null) {
            return responseResult;
        }
    }


    return null;
}




/**
     * 设置封面图片与素材的关系
     *
     * @param dto
     * @param materials
     * @param wmNews
     * @return
     */
    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        List<String> images = dto.getImages();
        //自动匹配封面
        if (dto.getType().equals(WemediaContans.WM_NEWS_AUTO_TYPE)) {
            //内容中的图片数量小于等于2  设置为单图
            if (materials.size() > 0 && materials.size() <= 2) {
                wmNews.setType(WemediaContans.WM_NEWS_SINGLE_TYPE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else if (materials.size() > 2) {
                //如果内容中的图片大于2 则设置为多图
                wmNews.setType(WemediaContans.WM_NEWS_MANY_TYPE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else {
                //内容中没有图片,则是无图
                wmNews.setType(WemediaContans.WM_NEWS_NONE_TYPE);
            }
            //修改文章信息
            if (images != null && images.size() > 0) {
                wmNews.setImages(images.toString().replace("[", "")
                        .replace("]", "").replace(fileServerUrl, "")
                        .replace(" ", ""));

            }
            updateById(wmNews);
        }
        //保存封面图片与素材的关系
        if (images != null && images.size() > 0) {
            ResponseResult responseResult = saveRelativeInfoForImage(images, wmNews.getId());
            if (responseResult != null) {
                return responseResult;
            }
        }
        return null;
}




/**
     * @param images
     * @param newsId
     * @return
     */
 private ResponseResult saveRelativeInfoForImage(List<String> images, Integer newsId) {
        List<String> materials = new ArrayList<>();
        for (String image : images) {
            materials.add(image.replace(fileServerUrl,""));
        }

        return saveRelativeInfo(materials,newsId,WemediaContans.WM_NEWS_COVER_REFERENCE);
}


3.7.控制器编写及测试

1.在heima-leadnews-wemedia中的WmNewsController中完善方法

@RestController
@RequestMapping("/api/v1/news")
public class WmNewsController implements WmNewsControllerApi {

    @Autowired
    private WmNewsService wmNewsService;

    ......
    
    @PostMapping("/submit")
    @Override
    public ResponseResult submitNews(@RequestBody WmNewsDto dto) {
        if(dto.getStatus() == WmNews.Status.SUBMIT.getCode()){
            return wmNewsService.saveNews(dto,WmNews.Status.SUBMIT.getCode());
        }else{
            return wmNewsService.saveNews(dto,WmNews.Status.NORMAL.getCode());
        }
    }
}

2.启动测试

需要启动的组件

  • heima-leadnews-wemedia-gateway
  • heima-leadnews-wemedia
  • heima-leadnews-admin-gateway
  • heima-leadnews-admin
  • nacos
  • seata
  • 前端项目

浏览器输入地址:localhost:8080,访问前端项目进行测试

4.自媒体文章-详情查询

4.1.需求分析

1604283242795

点击修改的时候,就是根据文章id查询,跳转至编辑页面进行展示

1604283268167

4.2.功能实现

1.在heima-leadnews-apis中的WmNewsControllerApi新增接口

public interface WmNewsControllerApi {

    .......

    /**
     * 根据id获取文章信息
     * @param id
     * @return
     */
    public ResponseResult findWmNewsById(Integer id);

    
}

2.在heima-leadnews-wemedia的WmNewsService新增接口

public interface WmNewsService extends IService<WmNews> {

    ......

    /**
     * 根据id获取文章信息
     * @param id
     * @return
     */
    public ResponseResult findWmNewsById(Integer id);
}

3.在heima-leadnews-wemedia的WmNewsServiceImpl中实现方法

/**
 * 根据id获取文章信息
 * @param id
 * @return
 */
@Override
public ResponseResult findWmNewsById(Integer id) {
    //1.参数检查
    if(id == null){
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
    }
    //2.查询数据
    WmNews wmNews = getById(id);
    if(wmNews == null){
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
    }

    //3.结果返回
    ResponseResult responseResult = ResponseResult.okResult(wmNews);
    responseResult.setHost(fileServerUrl);
    return responseResult;
}

4.在heima-leadnews-wemedia的WmNewsController中实现接口方法

@RestController
@RequestMapping("/api/v1/news")
public class WmNewsController implements WmNewsControllerApi {

    @Autowired
    private WmNewsService wmNewsService;

    ......

    @GetMapping("/one/{id}")
    @Override
    public ResponseResult findWmNewsById(@PathVariable("id") Integer id) {
        return wmNewsService.findWmNewsById(id);
    }
}

5.启动测试

5.自媒体文章-删除

5.1.需求分析

1604284123474

注意

  • 当文章状态为9(已发布)且已上架则不能删除文章,下架状态可以删除,如果是其他状态可以删除
  • 删除文章之前需要先把素材与文章的关系删除掉

5.2.功能实现

1.在heima-leadnews-apis中的WmNewsControllerApi新增接口

public interface WmNewsControllerApi {

   .......

    /**
     * 删除文章
     * @param id
     * @return
     */
    public ResponseResult delNews(Integer id);
}

2.在heima-leadnews-wemedia的WmNewsService新增接口

public interface WmNewsService extends IService<WmNews> {

    ......

    /**
     * 删除文章
     * @param id
     * @return
     */
    public ResponseResult delNews(Integer id);
    
}

3.在heima-leadnews-wemedia的WmNewsServiceImpl中实现方法

/**
 * 删除文章
 * @param id
 * @return
 */
@Override
public ResponseResult delNews(Integer id) {
    //1.检查参数
    if(id == null){
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
    }
    //2.获取数据
    WmNews wmNews = getById(id);
    if(wmNews == null){
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
    }

    //3.判断当前文章的状态  status==9  enable == 1
    if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaContans.WM_NEWS_ENABLE_UP)){
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布,不能删除");
    }

    //4.去除素材与文章的关系
    wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));

    //5.删除文章
    removeById(wmNews.getId());
    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}

4.在heima-leadnews-wemedia的WmNewsController中实现接口方法

@RestController
@RequestMapping("/api/v1/news")
public class WmNewsController implements WmNewsControllerApi {

    @Autowired
    private WmNewsService wmNewsService;

    ........

    @GetMapping("/del_news/{id}")
    @Override
    public ResponseResult delNews(@PathVariable("id") Integer id) {
        return wmNewsService.delNews(id);
    }
}

5.启动测试

6.自媒体文章-上架和下架

6.1.需求分析

下架

1604284831071

上架

1604284853373

注意

  • 当前已经发布(状态为9)的文章可以上架(enable = 1),也可以下架(enable = 0)
  • 在上架和下架操作的同时,需要同步app端的文章配置信息,暂时不做,后期讲到审核文章的时候再优化

6.2.功能实现

1.在heima-leadnews-apis中的WmNewsControllerApi新增接口

public interface WmNewsControllerApi {

    ........

    /**
     * 文章上下架
     * @param dto
     * @return
     */
    public ResponseResult downOrUp(WmNewsDto dto);

}

2.在heima-leadnews-wemedia的WmNewsService新增接口

public interface WmNewsService extends IService<WmNews> {

    .....

    /**
     * 文章上下架
     * @param dto
     * @return
     */
    public ResponseResult downOrUp(WmNewsDto dto);

}

3.在heima-leadnews-wemedia的WmNewsServiceImpl中实现方法

/**
 * 文章上下架
 * @param dto
 * @return
 */
@Override
public ResponseResult downOrUp(WmNewsDto dto) {
    //1.检查参数
    if(dto == null || dto.getId() == null){
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    //2.查询文章
    WmNews wmNews = getById(dto.getId());
    if(wmNews == null){
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
    }

    //3.判断文章是否发布
    if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态,不能上下架");
    }

    //4.修改文章状态,同步到app端(后期做)TODO
    if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
    }
    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}

4.在heima-leadnews-wemedia的WmNewsController中实现接口方法

@RestController
@RequestMapping("/api/v1/news")
public class WmNewsController implements WmNewsControllerApi {

    @Autowired
    private WmNewsService wmNewsService;

    .........

    @PostMapping("/down_or_up")
    @Override
    public ResponseResult downOrUp(@RequestBody WmNewsDto dto) {
        return wmNewsService.downOrUp(dto);
    }
}

5.启动测试