Parcourir la source

角色朋友圈

wuyi il y a 2 ans
Parent
commit
164d8b567b

+ 7 - 1
src/app.module.ts

@@ -20,6 +20,9 @@ import { MaskModule } from './mask/mask.module'
 import { WithdrawModule } from './withdraw/withdraw.module'
 import { SysConfigModule } from './sys-config/sys-config.module'
 import { AllExceptionsFilter } from './filters/all-exceptions-filter.filter'
+import { ChatRoleModule } from './chat-role/chat-role.module'
+import { LabelModule } from './label/label.module'
+import { MomentsModule } from './moments/moments.module'
 @Module({
     imports: [
         DevtoolsModule.register({
@@ -77,7 +80,10 @@ import { AllExceptionsFilter } from './filters/all-exceptions-filter.filter'
         UserBalanceModule,
         MaskModule,
         WithdrawModule,
-        SysConfigModule
+        SysConfigModule,
+        ChatRoleModule,
+        LabelModule,
+        MomentsModule
     ],
     controllers: [],
     providers: [

+ 82 - 0
src/chat-role/chat-role.controller.ts

@@ -0,0 +1,82 @@
+import {
+    Controller,
+    Put,
+    Get,
+    Body,
+    Param,
+    HttpStatus,
+    NotFoundException,
+    Delete,
+    BadRequestException,
+    Req,
+    Post
+} from '@nestjs/common'
+import { HasRoles } from '../auth/roles.decorator'
+import { Role } from '../model/role.enum'
+import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
+import { PageRequest } from '../common/dto/page-request'
+import { ChatRole } from './entities/chat-role.entity'
+import { ChatRoleDto } from './dto/chat-role.dto'
+import { ChatRoleService } from './chat-role.service'
+
+@ApiTags('chatRole')
+@Controller('/chatRole')
+@ApiBearerAuth()
+export class ChatRoleController {
+
+    constructor(private readonly chatRoleService: ChatRoleService) { }
+
+
+    @Post()
+    public async list(@Body() page: PageRequest<ChatRole>) {
+
+        return await this.chatRoleService.findAll(page)
+    }
+
+    @Get('/getRandom/:num')
+    public async randomQuery(@Param('num') num: number) {
+        return await this.chatRoleService.randomQuery(num)
+    }
+
+    @Put()
+    @HasRoles(Role.Admin)
+    public async create(@Body() chatRole: ChatRoleDto) {
+        return await this.chatRoleService.create(chatRole)
+    }
+
+    @Get('/get/:id')
+    public async get(@Param('id') id: string) {
+        const chatRole = await this.chatRoleService.findById(Number(id))
+        return chatRole
+    }
+
+    @Put('/:id')
+    @HasRoles(Role.Admin)
+    public async update(@Param('id') id: string, @Body() chatRoleDto: ChatRoleDto) {
+        try {
+            await this.chatRoleService.update(Number(id), chatRoleDto)
+
+            return {
+                message: 'ChatRole Updated successfully!',
+                status: HttpStatus.OK
+            }
+        } catch (err) {
+            throw new BadRequestException(err, 'Error: ChatRole not updated!')
+        }
+    }
+
+    @Delete('/:id')
+    @HasRoles(Role.Admin)
+    public async deleteMask(@Param('id') id: number) {
+        try {
+            await this.chatRoleService.delete(id)
+            return {
+                message: 'ChatRole Deleted successfully!',
+                status: HttpStatus.OK
+            }
+        } catch (err) {
+            throw new BadRequestException(err, 'Error: ChatRole not deleted!')
+        }
+    }
+
+}

+ 15 - 0
src/chat-role/chat-role.module.ts

@@ -0,0 +1,15 @@
+import { Module } from '@nestjs/common'
+import { TypeOrmModule } from '@nestjs/typeorm'
+import { ChatRole } from './entities/chat-role.entity'
+import { ChatRoleService } from './chat-role.service'
+import { ChatRoleController } from './chat-role.controller'
+import { LabelModule } from 'src/label/label.module'
+import { LabelService } from 'src/label/label.service'
+
+@Module({
+    imports: [TypeOrmModule.forFeature([ChatRole]), LabelModule],
+    controllers: [ChatRoleController],
+    providers: [ChatRoleService],
+    exports: [ChatRoleService]
+})
+export class ChatRoleModule { }

+ 101 - 0
src/chat-role/chat-role.service.ts

@@ -0,0 +1,101 @@
+import {
+    Injectable,
+    NotFoundException,
+    BadRequestException,
+} from '@nestjs/common'
+import { In, Repository, UpdateResult } from 'typeorm'
+import { InjectRepository } from '@nestjs/typeorm'
+import { ChatRole } from './entities/chat-role.entity'
+import { ChatRoleDto } from './dto/chat-role.dto'
+import { paginate, Pagination } from 'nestjs-typeorm-paginate'
+import { PageRequest } from '../common/dto/page-request'
+import { LabelService } from 'src/label/label.service'
+
+@Injectable()
+export class ChatRoleService {
+    constructor(
+        @InjectRepository(ChatRole)
+        private readonly chatRoleRepository: Repository<ChatRole>,
+        private readonly labelService: LabelService
+    ) { }
+
+    async findAll(req: PageRequest<ChatRole>): Promise<Pagination<ChatRole>> {
+        return await paginate<ChatRole>(this.chatRoleRepository, req.page, req.search)
+    }
+
+    async findMapByIds(ids: number[]): Promise<Map<number, ChatRole>> {
+        const chatRoleList = await this.chatRoleRepository.createQueryBuilder('chatRole')
+            .where({
+                id: In(ids),
+            }).getMany();
+
+        const chatRoleMap = new Map<number, ChatRole>();
+        for (let i = 0; i < chatRoleList.length; i++) {
+            const chatRole = chatRoleList[i];
+            const roleLabelList = await this.labelService.getRoleLabeltList(chatRole.id);
+
+            const labels: string[] = [];
+            roleLabelList.forEach(c => {
+                labels.push(c.describe);
+            });
+            chatRole.labels = labels;
+            chatRoleMap.set(chatRole.id, chatRole);
+        }
+
+        return chatRoleMap
+    }
+
+    async randomQuery(num: number): Promise<ChatRole[]> {
+        return await this.chatRoleRepository.createQueryBuilder().orderBy("RAND()").limit(num).getMany()
+    }
+
+    public async create(chatRoleDto: ChatRoleDto) {
+        const result = await this.chatRoleRepository.save(chatRoleDto)
+        this.labelService.addRoleLabel(result.id, chatRoleDto.labelList)
+        return result;
+    }
+
+    public async findById(id: number): Promise<ChatRole> {
+        const chatRole = await this.chatRoleRepository.findOneBy({
+            id: +id
+        })
+
+        if (!chatRole) {
+            throw new NotFoundException(`ChatRole #${id} not found`)
+        }
+
+        const roleLabelList = await this.labelService.getRoleLabeltList(id)
+        const labels: string[] = []
+        roleLabelList.forEach((c) => {
+            labels.push(c.describe)
+        })
+        chatRole.labels = labels
+        return chatRole
+    }
+
+    public async update(id: number, dto: ChatRoleDto): Promise<UpdateResult> {
+
+        try {
+            const chatRole = await this.chatRoleRepository.update(
+                {
+                    id: +id
+                },
+                { ...dto }
+            )
+
+            const oleList = await this.labelService.getRoleLabeltList(id)
+            await this.labelService.delRoleLabel(oleList)
+            this.labelService.addRoleLabel(id, dto.labelList)
+
+            return chatRole
+        } catch (err) {
+            throw new BadRequestException('ChatRole not updated')
+        }
+    }
+
+    public async delete(id: number): Promise<void> {
+        const chatRole = await this.findById(id)
+        await this.chatRoleRepository.remove(chatRole)
+    }
+
+}

+ 20 - 0
src/chat-role/dto/chat-role.dto.ts

@@ -0,0 +1,20 @@
+import { IsArray, IsNumber, IsString } from 'class-validator'
+import { Label } from 'src/label/entities/label.entity'
+
+export class ChatRoleDto {
+    @IsString()
+    name: string
+
+    @IsString()
+    describe: string
+
+    @IsNumber()
+    chatted?: number = 0
+
+    @IsNumber()
+    dynamicNumber?: number = 0
+
+    @IsArray()
+    labelList?: Label[]
+
+}

+ 32 - 0
src/chat-role/entities/chat-role.entity.ts

@@ -0,0 +1,32 @@
+import { Exclude } from 'class-transformer'
+import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn } from 'typeorm'
+import { ChatRoleDto } from '../dto/chat-role.dto'
+import { Label } from 'src/label/entities/label.entity'
+
+@Entity()
+export class ChatRole {
+    @PrimaryGeneratedColumn()
+    id: number
+
+    @Column()
+    name: string
+
+    @Column()
+    describe: string
+
+    @Column()
+    chatted: number
+
+    @Column()
+    dynamicNumber: number
+
+    @CreateDateColumn()
+    createdAt: Date
+
+    @Exclude()
+    labelList: Label[]
+
+    @Exclude()
+    labels: string[]
+
+}

+ 11 - 0
src/label/dto/label.dto.ts

@@ -0,0 +1,11 @@
+import { IsArray, IsNumber, IsString } from 'class-validator'
+
+export class LabelDto {
+
+    @IsNumber()
+    id: number
+
+    @IsString()
+    describe: string
+
+}

+ 13 - 0
src/label/entities/label.entity.ts

@@ -0,0 +1,13 @@
+import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn } from 'typeorm'
+
+@Entity()
+export class Label {
+    @PrimaryGeneratedColumn()
+    id: number
+
+    @Column()
+    describe: string
+
+    @CreateDateColumn()
+    createdAt: Date
+}

+ 19 - 0
src/label/entities/role-label.entity.ts

@@ -0,0 +1,19 @@
+import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn } from 'typeorm'
+
+@Entity()
+export class RoleLabel {
+    @PrimaryGeneratedColumn()
+    id: number
+
+    @Column()
+    roleId: number
+
+    @Column()
+    lableId: number
+
+    @Column()
+    describe: string
+
+    @CreateDateColumn()
+    createdAt: Date
+}

+ 22 - 0
src/label/label.controller.ts

@@ -0,0 +1,22 @@
+import {
+    Controller,
+    Put,
+    Get,
+    Body,
+    Param,
+    HttpStatus,
+    NotFoundException,
+    Delete,
+    BadRequestException,
+    Req,
+    Post
+} from '@nestjs/common'
+import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
+
+@ApiTags('label')
+@Controller('/label')
+@ApiBearerAuth()
+export class LabelController {
+
+
+}

+ 16 - 0
src/label/label.module.ts

@@ -0,0 +1,16 @@
+import { Module } from '@nestjs/common'
+import { TypeOrmModule } from '@nestjs/typeorm'
+import { Label } from './entities/label.entity'
+import { RoleLabel } from './entities/role-label.entity'
+import { LabelController } from './label.controller'
+import { LabelService } from './label.service'
+
+@Module({
+    imports: [TypeOrmModule.forFeature([Label,RoleLabel])],
+    controllers: [LabelController],
+    providers: [
+        LabelService
+    ],
+    exports: [LabelService]
+})
+export class LabelModule {}

+ 45 - 0
src/label/label.service.ts

@@ -0,0 +1,45 @@
+import {
+    Injectable,
+    NotFoundException,
+    BadRequestException,
+} from '@nestjs/common'
+import { InjectRepository } from '@nestjs/typeorm';
+import { Label } from './entities/label.entity';
+import { Repository } from 'typeorm';
+import { RoleLabel } from './entities/role-label.entity';
+
+@Injectable()
+export class LabelService {
+
+    constructor(
+        @InjectRepository(Label)
+        private readonly labelRepository: Repository<Label>,
+        @InjectRepository(RoleLabel)
+        private readonly roleLabelRepository: Repository<RoleLabel>
+    ) { }
+
+    async getRoleLabeltList(id: number): Promise<RoleLabel[]> {
+        return await this.roleLabelRepository.createQueryBuilder('roleLabel')
+            .where('roleLabel.roleId = :id', { id })
+            .getMany();
+    }
+
+    async addRoleLabel(roleId: number, labelList: Label[]): Promise<RoleLabel[]> {
+        const roleLabelList: RoleLabel[] = []
+
+        labelList.forEach((label) => {
+            const roleLabel = new RoleLabel()
+            roleLabel.roleId = roleId
+            roleLabel.lableId = label.id
+            roleLabel.describe = label.describe
+            roleLabelList.push(roleLabel)
+        })
+
+        return await this.roleLabelRepository.save(roleLabelList)
+    }
+
+    async delRoleLabel(list: RoleLabel[]): Promise<void> {
+        await this.roleLabelRepository.recover(list)
+    }
+
+}

+ 2 - 2
src/mask/mask.admin.controller.ts

@@ -23,7 +23,7 @@ import { MaskService } from './mask.service'
 @Controller('/admin/mask')
 @ApiBearerAuth()
 export class MaskAdminController {
-    constructor(private readonly maskService: MaskService) {}
+    constructor(private readonly maskService: MaskService) { }
 
 
     @Post()
@@ -32,7 +32,7 @@ export class MaskAdminController {
     }
 
     @Get('/getRandom/:num')
-    public async randomQuery(@Param('num') num: number){
+    public async randomQuery(@Param('num') num: number) {
         return await this.maskService.randomQuery(num)
     }
 

+ 9 - 0
src/moments/dto/moments.dto.ts

@@ -0,0 +1,9 @@
+import { IsString } from 'class-validator'
+
+export class MomentsDto {
+    @IsString()
+    name: string
+
+    @IsString()
+    content: string
+}

+ 25 - 0
src/moments/entities/moments.entity.ts

@@ -0,0 +1,25 @@
+import { Exclude } from 'class-transformer'
+import { ChatRole } from 'src/chat-role/entities/chat-role.entity'
+import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn } from 'typeorm'
+
+@Entity()
+export class Moments {
+    @PrimaryGeneratedColumn()
+    id: number
+
+    @Column()
+    userId: number
+
+    @Column()
+    title: string
+
+    @Column()
+    content: string
+
+    @CreateDateColumn()
+    createdAt: Date
+
+    @Exclude()
+    chatRole: ChatRole
+
+}

+ 19 - 0
src/moments/moments.controller.ts

@@ -0,0 +1,19 @@
+import { Body, Controller, Post } from "@nestjs/common";
+import { ApiBearerAuth, ApiTags } from "@nestjs/swagger";
+import { MomentsService } from "./moments.service";
+import { PageRequest } from "src/common/dto/page-request";
+import { Moments } from "./entities/moments.entity";
+
+@ApiTags('moments')
+@Controller('/moments')
+@ApiBearerAuth()
+export class MomentsController {
+
+    constructor(private readonly momentsService: MomentsService) { }
+
+    @Post()
+    public async page(@Body() page: PageRequest<Moments>) {
+        return await this.momentsService.findAll(page)
+    }
+
+}

+ 15 - 0
src/moments/moments.module.ts

@@ -0,0 +1,15 @@
+import { Module } from '@nestjs/common'
+import { TypeOrmModule } from '@nestjs/typeorm'
+import { Moments } from './entities/moments.entity'
+import { MomentsController } from './moments.controller'
+import { MomentsService } from './moments.service'
+import { ChatRoleModule } from 'src/chat-role/chat-role.module'
+import { ChatRoleService } from 'src/chat-role/chat-role.service'
+
+@Module({
+    imports: [TypeOrmModule.forFeature([Moments]), ChatRoleModule],
+    controllers: [MomentsController],
+    providers: [MomentsService],
+    exports: [MomentsService]
+})
+export class MomentsModule { }

+ 56 - 0
src/moments/moments.service.ts

@@ -0,0 +1,56 @@
+import {
+    Injectable,
+    NotFoundException,
+    HttpException,
+    HttpStatus,
+    BadRequestException,
+    InternalServerErrorException,
+    UnauthorizedException
+} from '@nestjs/common'
+import { Repository, UpdateResult } from 'typeorm'
+import { InjectRepository } from '@nestjs/typeorm'
+import { Moments } from './entities/moments.entity'
+
+import { paginate, Pagination } from 'nestjs-typeorm-paginate'
+import { PageRequest } from '../common/dto/page-request'
+import { ChatRoleService } from 'src/chat-role/chat-role.service'
+
+@Injectable()
+export class MomentsService {
+    constructor(
+        @InjectRepository(Moments)
+        private readonly momentsRepository: Repository<Moments>,
+        private readonly chatRoleService: ChatRoleService
+    ) { }
+
+    async findAll(req: PageRequest<Moments>): Promise<Pagination<Moments>> {
+        const page = await paginate<Moments>(this.momentsRepository, req.page, req.search)
+        const ids = page.items.reduce((ids: number[], val: Moments) => {
+            if (!ids.includes(val.userId)) {
+                ids.push(val.userId);
+            }
+            return ids;
+        }, []);
+
+        const map = await this.chatRoleService.findMapByIds(ids);
+        page.items.forEach(c => {
+            c.chatRole = map.get(c.userId)
+        })
+
+        return page
+    }
+
+
+    public async findById(id: number): Promise<Moments> {
+        const moments = await this.momentsRepository.findOneBy({
+            id: +id
+        })
+
+        if (!moments) {
+            throw new NotFoundException(`Monents #${id} not found`)
+        }
+
+        return moments
+    }
+
+}