mirror of https://github.com/fantasticit/think.git
server: support get comment without login
This commit is contained in:
parent
a7fb655f4c
commit
b77a7d2ffe
|
@ -1,5 +1,6 @@
|
|||
import { CommentDto, UpdateCommentDto } from '@dtos/comment.dto';
|
||||
import { JwtGuard } from '@guard/jwt.guard';
|
||||
import { UserGuard } from '@guard/user.guard';
|
||||
import {
|
||||
Body,
|
||||
ClassSerializerInterceptor,
|
||||
|
@ -63,8 +64,9 @@ export class CommentController {
|
|||
@UseInterceptors(ClassSerializerInterceptor)
|
||||
@Get(CommentApiDefinition.documents.server)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@UseGuards(JwtGuard)
|
||||
async getArticleComments(@Param('documentId') documentId, @Query() qurey) {
|
||||
return this.commentService.getDocumentComments(documentId, qurey);
|
||||
@UseGuards(UserGuard)
|
||||
async getArticleComments(@Request() req, @Param('documentId') documentId, @Query() qurey) {
|
||||
const user = req.user;
|
||||
return this.commentService.getDocumentComments(user, documentId, qurey);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { IUser } from '@think/domains';
|
||||
|
||||
@Injectable()
|
||||
export class UserGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = request?.cookies['token'];
|
||||
const user = this.jwtService.decode(token) as IUser;
|
||||
request.user = user;
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -92,7 +92,9 @@ export class CommentService {
|
|||
* @param documentId
|
||||
* @param queryParams
|
||||
*/
|
||||
async getDocumentComments(documentId, queryParams) {
|
||||
async getDocumentComments(user, documentId, queryParams) {
|
||||
const hasLogin = user ? !!(await this.userService.validateUser(user)) : false;
|
||||
|
||||
const query = this.commentRepo
|
||||
.createQueryBuilder('comment')
|
||||
.where('comment.documentId=:documentId')
|
||||
|
@ -116,9 +118,19 @@ export class CommentService {
|
|||
|
||||
const getCreateUser = async (comment) => {
|
||||
try {
|
||||
if (hasLogin) {
|
||||
const createUser = await this.userService.findById(comment.createUserId);
|
||||
comment.createUser = createUser;
|
||||
} else {
|
||||
comment.createUser = {
|
||||
id: comment.createUserId,
|
||||
name: `用户${comment.createUserId.split('-').shift()}`,
|
||||
role: 'normal',
|
||||
status: 'normal',
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('error', e);
|
||||
comment.createUser = null;
|
||||
}
|
||||
};
|
||||
|
|
Loading…
Reference in New Issue