实现博客评论

This commit is contained in:
2025-06-07 15:19:43 +08:00
parent 2627c85ec5
commit e646b20456
9 changed files with 123 additions and 23 deletions

View File

@@ -1,11 +1,15 @@
import { BadRequestException, Body, Controller, Get, Param, ParseUUIDPipe, Post } from '@nestjs/common';
import { BadRequestException, Body, Controller, Get, Param, ParseUUIDPipe, Post, Req, Request, UseGuards } from '@nestjs/common';
import { BlogService } from './blog.service';
import { OptionalAuthGuard } from 'src/auth/strategies/OptionalAuthGuard';
import { UserService } from 'src/user/user.service';
import { createBlogCommentDto } from './dto/create.blogcomment.dto';
@Controller('blog')
export class BlogController {
constructor(
private readonly blogService: BlogService,
private readonly userService: UserService,
) { }
@Get()
@@ -42,18 +46,24 @@ export class BlogController {
return await this.blogService.getComments(id);
}
// TODO鉴权该接口允许匿名评论但仍需验证userId合法性
// 该接口允许匿名评论但仍需验证userId合法性
@UseGuards(OptionalAuthGuard)
@Post(':id/comment')
async createBlogComment(
@Param('id', new ParseUUIDPipe({ version: '4' })) id: string,
@Body() commentData: { content: string },
@Body() commentData: createBlogCommentDto,
@Request() req,
) {
const { userId } = req.user || {};
const blog = await this.blogService.findById(id);
if (!blog) throw new BadRequestException('文章不存在');
let user = userId ? await this.userService.findOne({ userId }) : null;
const comment = {
...commentData,
blogId: id,
user: user,
};
return await this.blogService.createComment(comment);