|
|
@@ -14,23 +14,42 @@ export class FishController {
|
|
|
async create(request: FastifyRequest<{ Body: CreateFishBody }>, reply: FastifyReply) {
|
|
|
try {
|
|
|
const fishData = request.body
|
|
|
-
|
|
|
- if (!fishData.id) {
|
|
|
- fishData.id = request.ip || 'unknown'
|
|
|
+
|
|
|
+ if (!fishData.ip) {
|
|
|
+ fishData.ip = request.ip || 'unknown'
|
|
|
}
|
|
|
|
|
|
// 检查是否已存在相同 ID 的记录
|
|
|
+ let existingFish: any = null
|
|
|
+
|
|
|
try {
|
|
|
- await this.fishService.findById(fishData.id)
|
|
|
- return reply.code(400).send({ message: '记录已存在' })
|
|
|
+ existingFish = await this.fishService.findById(fishData.id as string)
|
|
|
} catch (error) {
|
|
|
- // 记录不存在,可以继续创建
|
|
|
}
|
|
|
|
|
|
- const fish = await this.fishService.create(fishData)
|
|
|
+ let fish: any
|
|
|
+ let message: string
|
|
|
+
|
|
|
+ if (existingFish) {
|
|
|
+ const { id, ...allData } = fishData
|
|
|
+ const updateData: any = {}
|
|
|
+ Object.keys(allData).forEach(key => {
|
|
|
+ const value = allData[key as keyof typeof allData]
|
|
|
+ if (value !== undefined && value !== null && value !== '') {
|
|
|
+ updateData[key] = value
|
|
|
+ }
|
|
|
+ })
|
|
|
+
|
|
|
+ fish = await this.fishService.update(id as string, updateData)
|
|
|
+ message = '记录已存在,更新成功'
|
|
|
+ } else {
|
|
|
+ // 记录不存在,执行创建操作
|
|
|
+ fish = await this.fishService.create(fishData)
|
|
|
+ message = '创建成功'
|
|
|
+ }
|
|
|
|
|
|
return reply.code(201).send({
|
|
|
- message: '创建成功',
|
|
|
+ message,
|
|
|
fish: {
|
|
|
id: fish.id,
|
|
|
name: fish.name,
|
|
|
@@ -47,8 +66,8 @@ export class FishController {
|
|
|
}
|
|
|
})
|
|
|
} catch (error) {
|
|
|
- console.error('创建记录失败:', error)
|
|
|
- return reply.code(500).send({ message: '创建失败' })
|
|
|
+ console.error('创建/更新记录失败:', error)
|
|
|
+ return reply.code(500).send({ message: '操作失败' })
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -84,11 +103,11 @@ export class FishController {
|
|
|
async list(request: FastifyRequest<{ Querystring: ListFishQuery }>, reply: FastifyReply) {
|
|
|
try {
|
|
|
const query = request.query
|
|
|
-
|
|
|
+
|
|
|
if (request.user.role !== 'admin') {
|
|
|
query.ownerId = request.user.id
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
const result = await this.fishService.list(query)
|
|
|
|
|
|
return reply.send(result)
|