next.js搭建博客系统-07-发布文章(2)

323 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第8天,点击查看活动详情

文章系列:

next.js搭建博客系统-01-环境搭建

next.js搭建博客系统-02-实现Layout布局

next.js搭建博客系统-03-登录组件(登录弹窗)

next.js搭建博客系统-04-登录模块(验证码和登录)

next.js搭建博客系统-05-数据库操作

next.js搭建博客系统-06-发布文章(1)

next.js搭建博客系统-07-发布文章(2)

next.js搭建博客系统-08-ssr渲染首页文章列表

next.js搭建博客系统-09-ssr渲染文章详情页

next.js搭建博客系统-10-发布评论

next.js搭建博客系统-11-标签管理(1)

next.js搭建博客系统-12-标签管理(2)

上篇文章 写了 发布文章的 新建标签的逻辑

接下来开始编写 发布文章的 最后 几个步骤

包括 发布文章的 校验逻辑 和 接口的逻辑 和 数据库的逻辑

然后开始写发布文章,

1.先判断是否输入标题,如果没有输入标题,就提示用户输入标题

2.然后调 发布文章的接口,参数就是 标题,markdown数据,标签

3.当接口调取成功的时候,提示发布成功,并跳到用户中心 的页面

4.当接口调取失败的时候,提示发布失败

const handlePublish = () => {
    if (!title) {
      message.warning('请输入文章标题');
      return ;
    }
    request.post('/api/article/publish', {
      title,
      content,
      tagIds
    }).then((res: any) => {
      if (res?.code === 0) {
        userId ? push(`/user/${userId}`) : push('/');
        message.success('发布成功');
      } else {
        message.error(res?.msg || '发布失败');
      }
    })
  };

\

现在写下 发布文章的接口

新建 api/artice/publish.ts

1.引入数据库和user, tag, article三张数据表

import { prepareConnection } from 'db/index';
import { User, Article, Tag } from 'db/entity/index';

2.链接三个数据表

const db = await prepareConnection();
  const userRepo = db.getRepository(User);
  const articleRepo = db.getRepository(Article);
  const tagRepo = db.getRepository(Tag);

3.从req.body中获取传入的参数

const { title = '', content = '', tagIds = [] } = req.body;

4.从session中获取用户信息

const session: ISession = req.session;

5.根据session从user表中查询当前用户信息

const user = await userRepo.findOne({
    id: session.userId,
  });

6.根据传入的标签,获取所有的标签

const tags = await tagRepo.find({
    where: tagIds?.map((tagId: number) => ({ id: tagId })),
  });

7.将传入的数据 存入到 article表中, 如果有用户信息,将用户信息也存入表,并且标签数量增加

const article = new Article();
  article.title = title;
  article.content = content;
  article.create_time = new Date();
  article.update_time = new Date();
  article.is_delete = 0;
  article.views = 0;

if (user) {
    article.user = user;
  }

  if (tags) {
    const newTags = tags?.map((tag) => {
      tag.article_count = tag?.article_count + 1;
      return tag;
    });
    article.tags = newTags;
  }

  const resArticle = await articleRepo.save(article);

  if (resArticle) {
    res.status(200).json({ data: resArticle, code: 0, msg: '发布成功' });
  } else {
    res.status(200).json({ ...EXCEPTION_ARTICLE.PUBLISH_FAILED });
  }

这样就完成了文章发布