如何返回Prisma.$事务中拒绝操作的信息



我有一个数据库,我需要更新一些学生的成绩。我想使用Prisma事务和id/等级数组来更新数据库中的所有匹配记录。所有工作正常,直到在数据库上没有找到任何ID,在这种情况下,整个事务按预期失败,但没有关于哪个特定记录导致错误的信息。

我想要的是能够抛出一个自定义错误,指定未找到的ID,以便我可以提醒用户。

代码如下:


const grades = [
{id: 1, grade: '100'}
{id: 45, grade: '98' }
]
prisma.$transaction(
grades.map((el) => prisma.student.update({ 
where: { id: el.id },
data: { grade: el.grade }
})
)

这个工作直到在数据库上没有找到id,在这种情况下,它抛出一个错误,如:Record not found.问题是,它没有告诉我哪个id没有找到,所以我可以提醒用户。

我已经尝试在每个查询上放置一个捕获,所以我可以抛出一个自定义错误,所需的信息如下:

grades.map((el) => prisma.student.update({ 
where: { id: el.id },
data: { grade: el.grade }
}).catch((e) => throw new Error(`ID not found ${el.id}`)
)

此代码抛出以下类型错误,不能运行:

Argument of type 'Promise<Student>[]' is not assignable to parameter of type 'PrismaPromise<any>[]'.
Type 'Promise<Student>' is not assignable to type 'PrismaPromise<any>'.
Property '[prisma]' is missing in type 'Promise<Student>' but required in type '{ [prisma]: true; }'.

我如何提醒用户没有找到特定的ID ?

为什么不在事务之前运行一个查询,尝试在更新之前从数据库加载所有成绩?然后,您可以比较从数据库中加载的分数,如果在项目数量上存在差异,则查找缺少的项目并抛出错误。

const gradeIds = grades.map(grade => grade.id);
const dbGrades = await prisma.student.findMany({
// This only loads the ID from grades in the database to reduce
// the size of the query and only grab the necessary data
// for the operation
select: {id: true},
where: {id: {in: gradeIds}}
});
// If this condition is true, then some grades 
// from the "grades" variable could not have been loaded.
// Figure out what those grades are and throw an error.
if (dbGrades.length !== grades.length) {
const dbGradeIds = dbGrades.map(dbGrade => dbGrade.id);
const missingGrades = gradeIds.filter(gradeId => dbGradeIds.indexOf(gradeId) === -1);
throw new Error(`ID(s) not found: ${missingGrades.join(",")}`);
}
// Else, the number of items is the same, and every input grade has a corresponding
// item in the database, therefore you should be able to do the update without
// having to worry about a missing item

相关内容

最新更新