Skip to content

Commit

Permalink
评论ui优化
Browse files Browse the repository at this point in the history
  • Loading branch information
houdunwang committed May 25, 2023
1 parent aa759ea commit 118703c
Show file tree
Hide file tree
Showing 47 changed files with 822 additions and 105 deletions.
4 changes: 2 additions & 2 deletions hdcms/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"@nestjs/passport": "^9.0.3",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/throttler": "^4.0.0",
"@prisma/client": "^4.13.0",
"@prisma/client": "^4.14.1",
"@types/md5": "^2.3.2",
"argon2": "^0.30.3",
"cache-manager": "^5.2.1",
Expand Down Expand Up @@ -75,7 +75,7 @@
"eslint-plugin-prettier": "^4.0.0",
"jest": "29.5.0",
"prettier": "^2.3.2",
"prisma": "^4.13.0",
"prisma": "^4.14.1",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "29.0.5",
Expand Down
30 changes: 15 additions & 15 deletions hdcms/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 27 additions & 8 deletions hdcms/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,44 @@ datasource db {
}

model User {
id Int @id @default(autoincrement())
id Int @id @default(autoincrement())
name String
password String
nickname String?
secret String?
email String?
mobile String?
avatar String?
createAt DateTime @default(now())
updateAt DateTime @updatedAt
createAt DateTime @default(now())
updateAt DateTime @updatedAt
Comment Comment[]
}

model Soft {
id Int @id @default(autoincrement())
id Int @id @default(autoincrement())
title String
content String @db.Text
content String @db.Text
description String
preview String
is_free Boolean @default(true)
createAt DateTime @default(now())
updateAt DateTime @updatedAt
is_free Boolean @default(true)
createAt DateTime @default(now())
updateAt DateTime @updatedAt
Comment Comment[]
}

model Comment {
id Int @id @default(autoincrement())
content String
createAt DateTime @default(now())
updateAt DateTime @updatedAt
//发布者
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int
//软件
soft Soft @relation(fields: [softId], references: [id], onDelete: Cascade)
softId Int
//回复
commentId Int?
reply Comment? @relation("replys", fields: [commentId], references: [id], onDelete: Cascade)
replys Comment[] @relation("replys")
}
2 changes: 2 additions & 0 deletions hdcms/prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { comment } from './seed/comment'
import { soft } from './seed/soft'
import user from './seed/user'

async function run() {
await user()
await soft()
await comment()
}

run()
17 changes: 16 additions & 1 deletion hdcms/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'
import { Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { CommonModule } from './common/common.module'
Expand All @@ -7,6 +8,9 @@ import { UploadModule } from './upload/upload.module'
import { UserModule } from './user/user.module'
import { CaptchaModule } from './captcha/captcha.module'
import { CacheModule } from '@nestjs/cache-manager'
import { CommentModule } from './comment/comment.module'
import { PolicyModule } from './policy/policy.module'
import { APP_GUARD } from '@nestjs/core'
@Module({
imports: [
CommonModule,
Expand All @@ -19,8 +23,19 @@ import { CacheModule } from '@nestjs/cache-manager'
ttl: 600,
isGlobal: true,
}),
CommentModule,
PolicyModule,
ThrottlerModule.forRoot({
ttl: 60,
limit: 10,
}),
],
controllers: [AppController],
providers: [],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class AppModule {}
44 changes: 44 additions & 0 deletions hdcms/src/comment/comment.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Body, Controller, Delete, Get, Param, Post, UseGuards } from '@nestjs/common'
import { User } from '@prisma/client'
import { Auth } from 'src/auth/auth.decorator'
import { CurrentUser } from 'src/auth/current-user.decorator'
import { PrismaService } from 'src/common/prisma.service'
import { Policy } from 'src/policy/policy.decorator'
import { PolicyGuard } from 'src/policy/policy.guard'
import { CommentPolicy } from './comment.policy'
import { CommentResponse } from './comment.response'
import { CommentService } from './comment.service'
import { CreateCommentDto } from './dto/create-comment.dto'
import { Throttle } from '@nestjs/throttler'

@Controller('comment/:sid')
export class CommentController {
constructor(private readonly commentService: CommentService, private prisma: PrismaService) {}

@Post()
@Auth()
@Throttle(190, 20)
async create(@Body() createCommentDto: CreateCommentDto, @CurrentUser() user: User, @Param('sid') sid: number) {
const comment = await this.commentService.create(createCommentDto, user, sid)
return new CommentResponse(comment).make()
}

@Get()
async findAll(@Param('sid') sid: number) {
const comments = await this.commentService.findAll(+sid)
return comments.map((comment) => {
return new CommentResponse(comment).make()
})
}

@Delete(':id')
//守卫:执行验证
@UseGuards(PolicyGuard)
//设置元数据,提供给守卫
@Policy(CommentPolicy)
//获取身份、登录
@Auth()
async remove(@Param('id') id: string, @CurrentUser() user: User) {
return this.commentService.remove(+id)
}
}
9 changes: 9 additions & 0 deletions hdcms/src/comment/comment.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { CommentService } from './comment.service';
import { CommentController } from './comment.controller';

@Module({
controllers: [CommentController],
providers: [CommentService]
})
export class CommentModule {}
12 changes: 12 additions & 0 deletions hdcms/src/comment/comment.policy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Comment, User } from '@prisma/client'
import { Request } from 'express'
import { PrismaService } from 'src/common/prisma.service'
import { IPolicy } from 'src/policy/policy.decorator'

export class CommentPolicy implements IPolicy {
constructor(private prisma: PrismaService, private request: Request) {}

remove(model: Comment, user: User) {
return model.userId == user.id
}
}
13 changes: 13 additions & 0 deletions hdcms/src/comment/comment.response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Comment, User } from '@prisma/client'
import { JsonResponse } from 'src/core/json.response'
import { UserResponse } from 'src/user/user.response'

export class CommentResponse extends JsonResponse<Comment & { user: User }> {
// protected hidden: (keyof User)[] = ['password']
public make(): Comment & { user: User } {
super.make()
this.data.user = new UserResponse(this.data.user).make()
// this.data.user = JsonResponse.handle(this.data.user, ['password', 'secret', 'mobile'])
return this.data
}
}
39 changes: 39 additions & 0 deletions hdcms/src/comment/comment.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Injectable } from '@nestjs/common'
import { CreateCommentDto } from './dto/create-comment.dto'
import { UpdateCommentDto } from './dto/update-comment.dto'
import { PrismaService } from 'src/common/prisma.service'
import { User } from '@prisma/client'

@Injectable()
export class CommentService {
constructor(private prisma: PrismaService) {}

create(createCommentDto: CreateCommentDto, user: User, sid: number) {
const { commentId, ...dto } = createCommentDto
return this.prisma.comment.create({
data: {
...dto,
soft: { connect: { id: +sid } },
user: { connect: { id: user.id } },
reply: commentId && { connect: { id: +commentId } },
},
include: {
replys: true,
user: true,
},
})
}

findAll(sid: number) {
return this.prisma.comment.findMany({
where: {
softId: sid,
},
include: { user: true, replys: true },
})
}

remove(id: number) {
return this.prisma.comment.deleteMany({ where: { id } })
}
}
10 changes: 10 additions & 0 deletions hdcms/src/comment/dto/create-comment.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Allow, IsNotEmpty, Length } from 'class-validator'

export class CreateCommentDto {
@IsNotEmpty({ message: '评论内容不能为空' })
@Length(10, 1000, { message: '评论内容不能少于10个字' })
content: string

@Allow()
commentId?: number
}
4 changes: 4 additions & 0 deletions hdcms/src/comment/dto/update-comment.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateCommentDto } from './create-comment.dto';

export class UpdateCommentDto extends PartialType(CreateCommentDto) {}
1 change: 1 addition & 0 deletions hdcms/src/comment/entities/comment.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class Comment {}
6 changes: 6 additions & 0 deletions hdcms/src/policy/policy.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { SetMetadata } from '@nestjs/common'

export interface IPolicy {}
export const POLICY_KEY = 'policy_key'

export const Policy = (policy: IPolicy, action?: string) => SetMetadata(POLICY_KEY, { policy, action })
27 changes: 27 additions & 0 deletions hdcms/src/policy/policy.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { Observable } from 'rxjs'
import { POLICY_KEY } from './policy.decorator'
import { PrismaService } from 'src/common/prisma.service'
import { Request } from 'express'
import { User } from '@prisma/client'

@Injectable()
export class PolicyGuard implements CanActivate {
constructor(private readonly reflector: Reflector, private readonly prisma: PrismaService) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const { policy, action } = this.reflector.get<any>(POLICY_KEY, context.getHandler())
const controller = context.getClass().name.replace('Controller', '')
const method = context.getHandler().name
const request = context.switchToHttp().getRequest() as Request
const user = request.user as User
//超管放行
if (user?.id == 1) return true
const model = await this.prisma[controller].findUnique({
where: { id: +(request.params.id || 0) },
})
const policyInstance = new policy(this.prisma, request)
return policyInstance[action || method](model, user)
}
}
4 changes: 4 additions & 0 deletions hdcms/src/policy/policy.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { Module } from '@nestjs/common';

@Module({})
export class PolicyModule {}
6 changes: 3 additions & 3 deletions hdcms/src/soft/dto/create-soft.dto.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { IsNotEmpty } from 'class-validator'

export class CreateSoftDto {
@IsNotEmpty()
@IsNotEmpty({ message: '软件名称不能为空' })
title: string

@IsNotEmpty()
@IsNotEmpty({ message: '软件说明不能为空' })
content: string

@IsNotEmpty()
@IsNotEmpty({ message: '软件截图不能为空' })
preview: string
@IsNotEmpty({ message: '软件简介不能为空' })
description: string
Expand Down
4 changes: 2 additions & 2 deletions hdcms/src/soft/soft.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export class SoftController {
}

@Get()
findAll(@Query('page') page: number) {
return this.softService.findAll(+page)
findAll(@Query('page') page: number = 1, @Query('row') row: number = 10) {
return this.softService.findAll(+page, +row)
}

@Get(':id')
Expand Down
Loading

0 comments on commit 118703c

Please sign in to comment.