library-picturebook-activity/backend/src/contests/attachments/attachments.service.ts

109 lines
2.3 KiB
TypeScript
Raw Normal View History

import {
Injectable,
NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreateAttachmentDto } from './dto/create-attachment.dto';
import { UpdateAttachmentDto } from './dto/update-attachment.dto';
@Injectable()
export class AttachmentsService {
constructor(private prisma: PrismaService) {}
async create(createAttachmentDto: CreateAttachmentDto, creatorId?: number) {
// 验证活动是否存在
const contest = await this.prisma.contest.findUnique({
where: { id: createAttachmentDto.contestId },
});
if (!contest) {
throw new NotFoundException('活动不存在');
}
const data: any = {
...createAttachmentDto,
size: createAttachmentDto.size || '0',
};
if (creatorId) {
data.creator = creatorId;
}
return this.prisma.contestAttachment.create({
data,
include: {
contest: true,
},
});
}
async findAll(contestId: number) {
return this.prisma.contestAttachment.findMany({
where: {
contestId,
validState: 1,
},
orderBy: {
createTime: 'desc',
},
include: {
contest: {
select: {
id: true,
contestName: true,
},
},
},
});
}
async findOne(id: number) {
const attachment = await this.prisma.contestAttachment.findFirst({
where: {
id,
validState: 1,
},
include: {
contest: true,
},
});
if (!attachment) {
throw new NotFoundException('附件不存在');
}
return attachment;
}
async update(id: number, updateAttachmentDto: UpdateAttachmentDto, modifierId?: number) {
const attachment = await this.findOne(id);
const data: any = { ...updateAttachmentDto };
if (modifierId) {
data.modifier = modifierId;
}
return this.prisma.contestAttachment.update({
where: { id },
data,
include: {
contest: true,
},
});
}
async remove(id: number) {
await this.findOne(id);
// 软删除
return this.prisma.contestAttachment.update({
where: { id },
data: {
validState: 2,
},
});
}
}