67 lines
2.3 KiB
TypeScript
67 lines
2.3 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { Prisma } from '@prisma/client';
|
|
import { ErrorCode, JobStatus, JobType, RoleType } from '@artveris/shared';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
import { BusinessException } from '../common/exceptions/business.exception';
|
|
import { buildPage } from '../common/utils/pagination.util';
|
|
import { AuthUser } from '../common/decorators/current-user.decorator';
|
|
import { QueryJobDto } from './dto/query-job.dto';
|
|
|
|
@Injectable()
|
|
export class JobsService {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
create(type: JobType, total: number, createdBy?: number, payload?: Prisma.InputJsonValue) {
|
|
return this.prisma.job.create({
|
|
data: { type, total, createdBy, payload, status: JobStatus.PENDING },
|
|
});
|
|
}
|
|
|
|
start(id: string) {
|
|
return this.prisma.job.update({ where: { id }, data: { status: JobStatus.PROCESSING } });
|
|
}
|
|
|
|
progress(id: string, successCount: number, failCount: number) {
|
|
return this.prisma.job.update({ where: { id }, data: { successCount, failCount } });
|
|
}
|
|
|
|
finish(
|
|
id: string,
|
|
data: {
|
|
status: JobStatus;
|
|
successCount?: number;
|
|
failCount?: number;
|
|
resultFileUrl?: string | null;
|
|
error?: string | null;
|
|
},
|
|
) {
|
|
return this.prisma.job.update({ where: { id }, data });
|
|
}
|
|
|
|
async get(id: string, user?: AuthUser) {
|
|
const job = await this.prisma.job.findUnique({ where: { id } });
|
|
if (!job) throw new BusinessException(ErrorCode.JOB_NOT_FOUND, '任务不存在', 404);
|
|
if (user && user.role !== RoleType.SUPER_ADMIN && job.createdBy !== user.id) {
|
|
throw new BusinessException(ErrorCode.FORBIDDEN, '没有访问该任务的权限', 403);
|
|
}
|
|
return job;
|
|
}
|
|
|
|
async list(query: QueryJobDto, user?: AuthUser) {
|
|
const where: Prisma.JobWhereInput = {};
|
|
if (query.type) where.type = query.type;
|
|
if (query.status) where.status = query.status;
|
|
if (user && user.role !== RoleType.SUPER_ADMIN) where.createdBy = user.id;
|
|
const [list, total] = await this.prisma.$transaction([
|
|
this.prisma.job.findMany({
|
|
where,
|
|
orderBy: { createdAt: 'desc' },
|
|
skip: query.skip,
|
|
take: query.take,
|
|
}),
|
|
this.prisma.job.count({ where }),
|
|
]);
|
|
return buildPage(list, total, query.page, query.pageSize);
|
|
}
|
|
}
|