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

lzfw57am  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(149)

我有一个数据库,其中包含一些需要更新成绩的学生。我想使用Prisma事务和一个id/grades数组来更新数据库中所有匹配的记录。所有工作都很正常,直到在数据库中找不到任何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没有找到,所以我可以提醒用户。
我已经尝试过在每个查询上添加一个catch,这样我就可以抛出一个包含所需信息的自定义错误,如下所示:

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?

xtfmy6hx

xtfmy6hx1#

为什么不在事务处理之前运行一个查询,尝试在更新之前从数据库加载所有等级?然后,可以比较从数据库加载的等级,如果项目数不同,则查找缺少的项目并引发错误。

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

相关问题