Ver código fonte

聊天记录列表

wui 7 meses atrás
pai
commit
ee030039a8

+ 2 - 0
src/app.ts

@@ -8,6 +8,7 @@ import fastifyEnv, { FastifyEnvOptions } from '@fastify/env'
 import { schema } from './config/env'
 import { schema } from './config/env'
 import { createDataSource } from './config/database'
 import { createDataSource } from './config/database'
 import userRoutes from './routes/user.routes'
 import userRoutes from './routes/user.routes'
+import recordsRoutes from './routes/records.routes'
 import { config } from 'dotenv'
 import { config } from 'dotenv'
 
 
 config()
 config()
@@ -65,6 +66,7 @@ const start = async () => {
   })
   })
 
 
   app.register(userRoutes, { prefix: '/api/users' })
   app.register(userRoutes, { prefix: '/api/users' })
+  app.register(recordsRoutes, { prefix: '/api/records' })
 
 
   const dataSource = createDataSource(app)
   const dataSource = createDataSource(app)
   await dataSource.initialize()
   await dataSource.initialize()

+ 130 - 0
src/controllers/records.controller.ts

@@ -0,0 +1,130 @@
+import { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify'
+import { RecordsService } from '../services/records.service'
+import {
+  ListRecordsQuery,
+  CreateRecordsBody,
+  UpdateRecordsBody
+} from '../dto/records.dto'
+
+export class RecordsController {
+  private recordsService: RecordsService
+
+  constructor(app: FastifyInstance) {
+    this.recordsService = new RecordsService(app)
+  }
+
+  async create(request: FastifyRequest<{ Body: CreateRecordsBody }>, reply: FastifyReply) {
+    try {
+      const { url, description } = request.body
+
+      if (!url || !description) {
+        return reply.code(400).send({ message: 'URL和描述不能为空' })
+      }
+
+      const record = await this.recordsService.create(url, description)
+
+      return reply.code(201).send({
+        record: {
+          id: record.id,
+          url: record.url,
+          description: record.description,
+          createdAt: record.createdAt,
+          updatedAt: record.updatedAt
+        }
+      })
+    } catch (error) {
+      return reply.code(500).send(error)
+    }
+  }
+
+  async list(request: FastifyRequest<{ Querystring: ListRecordsQuery }>, reply: FastifyReply) {
+    try {
+      const { page, size, url, description } = request.query
+
+      const result = await this.recordsService.findAll(page, size, url, description)
+
+      return reply.send(result)
+    } catch (error) {
+      return reply.code(500).send(error)
+    }
+  }
+
+  async getById(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
+    try {
+      const id = parseInt(request.params.id)
+      
+      if (isNaN(id)) {
+        return reply.code(400).send({ message: '无效的ID' })
+      }
+
+      const record = await this.recordsService.findById(id)
+
+      return reply.send({
+        record: {
+          id: record.id,
+          url: record.url,
+          description: record.description,
+          createdAt: record.createdAt,
+          updatedAt: record.updatedAt
+        }
+      })
+    } catch (error) {
+      if (error && typeof error === 'object' && 'name' in error && error.name === 'EntityNotFoundError') {
+        return reply.code(404).send({ message: '记录不存在' })
+      }
+      return reply.code(500).send(error)
+    }
+  }
+
+  async update(request: FastifyRequest<{ Body: UpdateRecordsBody }>, reply: FastifyReply) {
+    try {
+      const { id, url, description } = request.body
+
+      if (!id) {
+        return reply.code(400).send({ message: 'ID不能为空' })
+      }
+
+      try {
+        await this.recordsService.findById(id)
+      } catch (error) {
+        return reply.code(404).send({ message: '记录不存在' })
+      }
+
+      const updatedRecord = await this.recordsService.updateRecord(id, { url, description })
+
+      return reply.send({
+        record: {
+          id: updatedRecord.id,
+          url: updatedRecord.url,
+          description: updatedRecord.description,
+          createdAt: updatedRecord.createdAt,
+          updatedAt: updatedRecord.updatedAt
+        }
+      })
+    } catch (error) {
+      return reply.code(500).send(error)
+    }
+  }
+
+  async delete(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
+    try {
+      const id = parseInt(request.params.id)
+      
+      if (isNaN(id)) {
+        return reply.code(400).send({ message: '无效的ID' })
+      }
+
+      try {
+        await this.recordsService.findById(id)
+      } catch (error) {
+        return reply.code(404).send({ message: '记录不存在' })
+      }
+
+      await this.recordsService.deleteRecord(id)
+
+      return reply.send({ message: '记录删除成功' })
+    } catch (error) {
+      return reply.code(500).send(error)
+    }
+  }
+} 

+ 17 - 0
src/dto/records.dto.ts

@@ -0,0 +1,17 @@
+import { Pagination } from './common.dto'
+
+export interface CreateRecordsBody {
+  url: string
+  description: string
+}
+
+export interface UpdateRecordsBody {
+  id: number
+  url?: string
+  description?: string
+}
+
+export interface ListRecordsQuery extends Pagination {
+  url?: string
+  description?: string
+} 

+ 19 - 0
src/entities/records.entity.ts

@@ -0,0 +1,19 @@
+import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm'
+
+@Entity()
+export class Records {
+  @PrimaryGeneratedColumn()
+  id: number
+
+  @Column({ length: 1024 })
+  url: string
+
+  @Column()
+  description: string
+
+  @CreateDateColumn()
+  createdAt: Date
+
+  @UpdateDateColumn()
+  updatedAt: Date
+}

+ 44 - 0
src/routes/records.routes.ts

@@ -0,0 +1,44 @@
+import { FastifyInstance } from 'fastify'
+import { RecordsController } from '../controllers/records.controller'
+import { authenticate, hasRole } from '../middlewares/auth.middleware'
+import { ListRecordsQuery, CreateRecordsBody, UpdateRecordsBody } from '../dto/records.dto'
+import { UserRole } from '../entities/user.entity'
+
+export default async function recordsRoutes(fastify: FastifyInstance) {
+  const recordsController = new RecordsController(fastify)
+
+  // 创建记录
+  fastify.post<{ Body: CreateRecordsBody }>(
+    '/',
+    { onRequest: [authenticate] },
+    recordsController.create.bind(recordsController)
+  )
+
+  // 获取记录列表
+  fastify.get<{ Querystring: ListRecordsQuery }>(
+    '/',
+    { onRequest: [authenticate] },
+    recordsController.list.bind(recordsController)
+  )
+
+  // 根据ID获取记录
+  fastify.get<{ Params: { id: string } }>(
+    '/:id',
+    { onRequest: [authenticate] },
+    recordsController.getById.bind(recordsController)
+  )
+
+  // 更新记录
+  fastify.put<{ Body: UpdateRecordsBody }>(
+    '/',
+    { onRequest: [authenticate] },
+    recordsController.update.bind(recordsController)
+  )
+
+  // 删除记录
+  fastify.delete<{ Params: { id: string } }>(
+    '/:id',
+    { onRequest: [authenticate] },
+    recordsController.delete.bind(recordsController)
+  )
+} 

+ 63 - 0
src/services/records.service.ts

@@ -0,0 +1,63 @@
+import { Repository, Like } from 'typeorm'
+import { FastifyInstance } from 'fastify'
+import { Records } from '../entities/records.entity'
+import { PaginationResponse } from '../dto/common.dto'
+
+export class RecordsService {
+  private recordsRepository: Repository<Records>
+
+  constructor(app: FastifyInstance) {
+    this.recordsRepository = app.dataSource.getRepository(Records)
+  }
+
+  async create(url: string, description: string): Promise<Records> {
+    const record = this.recordsRepository.create({
+      url,
+      description
+    })
+    return this.recordsRepository.save(record)
+  }
+
+  async findById(id: number): Promise<Records> {
+    return this.recordsRepository.findOneOrFail({ where: { id } })
+  }
+
+  async findAll(page: number = 0, size: number = 20, url?: string, description?: string): Promise<PaginationResponse<Records>> {
+    const where: any = {}
+    
+    if (url) {
+      where.url = Like(`%${url}%`)
+    }
+    
+    if (description) {
+      where.description = Like(`%${description}%`)
+    }
+
+    const [records, total] = await this.recordsRepository.findAndCount({
+      skip: (Number(page) || 0) * (Number(size) || 20),
+      take: Number(size) || 20,
+      where,
+      order: {
+        createdAt: 'DESC'
+      }
+    })
+
+    return {
+      content: records,
+      metadata: {
+        total: Number(total),
+        page: Number(page),
+        size: Number(size)
+      }
+    }
+  }
+
+  async updateRecord(id: number, data: Partial<Records>): Promise<Records> {
+    await this.recordsRepository.update(id, data)
+    return this.findById(id)
+  }
+
+  async deleteRecord(id: number): Promise<void> {
+    await this.recordsRepository.delete(id)
+  }
+}