Ways to access details on the rejection process within a Prisma.$transaction

I am facing an issue with my database and updating student grades using Prisma transactions. When any ID is not found in the database, the transaction fails without indicating which record caused the error.

I want to be able to throw a custom error that specifies the ID of the record that wasn't found so I can inform the user.

Below is the code snippet:


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 }
    })
)

However, when an ID is not found in the database, it throws a generic error message like Record not found., without detailing which specific ID caused the issue.

I have tried adding a catch block to throw a custom error with the relevant information as follows:


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

But this approach results in an error:

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; }'.

How can I modify the code to alert the user about which specific IDs are not found?

Answer №1

One approach to consider before proceeding with your transaction is running a query to fetch all grades from the database for comparison. By loading and comparing the grades retrieved from the database with the ones you intend to update, you can easily identify any missing items and handle them accordingly.

const gradeIds = grades.map(grade => grade.id);
const dbGrades = await prisma.student.findMany({
  // Retrieve only the ID of grades from the database to optimize the query
  select: {id: true},
  where: {id: {in: gradeIds}}
});
// If the number of loaded grades doesn't match the total input grades, 
// determine which grades are missing 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(`IDs not found: ${missingGrades.join(",")}`);
}
// Otherwise, proceed with the update as every input grade has a corresponding 
// entry in the database

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preventing an Angular component from continuing to execute after clicking away from it

At the moment, I have a sidebar with clickable individual components that trigger API calls to fetch data. However, I've noticed that even when I click off a component to another one, the old component continues to refresh the API data unnecessarily. ...

Is it possible to locate a Typescript class only when there are no references to its properties?

Currently, I am utilizing TypeScript 2.0 within VSCode and although the highlighted errors are being confirmed by the TypeScript compiler, they all point to a module that I am importing: import * as els from 'elasticsearch'; The module elastics ...

It only takes half a minute for ts-node-dev to set up its watchers

Having tried both ts-node and ts-node-dev, I am frustrated by the fact that they take almost the same amount of time to start my app server. This issue has been a recurring problem for me, with no successful attempts at resolving it. Currently, I am opera ...

Unable to locate the module '@vitejs/plugin-react' or its associated type

After creating the project with npm create vite@latest and selecting ts-react, everything seemed to work fine when I ran npm run dev. However, in my vs code editor, I encountered the error message "Cannot find module '@vitejs/plugin-react' or its ...

Which `target` is best for Node 11 in TypeScript?

With TypeScript's target configuration offering various values such as esnext, es2015, and es6, it can be a bit confusing to decide which one to choose. The latest version of NodeJs (11.11.0) supports many new JavaScript features. But is it recommend ...

A tutorial on ensuring Angular loads data prior to attempting to load a module

Just starting my Angular journey... Here's some code snippet: ngOnInit(): void { this.getProduct(); } getProduct(): void { const id = +this.route.snapshot.paramMap.get('id'); this.product = this.products.getProduct(id); ...

Unexpected patterns observed when utilizing parent/child routing files

I am working with a Node/Express backend that is implemented using TypeScript. Whenever I make changes to a file and save it, if I test the root route in Postman localhost:8000/, I receive the expected response. However, when I test localhost:8000/user af ...

The callback function `(err: any, data: any) => void` does not share any properties with the type `RequestInit`

Inspired by the tutorial at , I am working on a time-based visualization. I am currently using version "d3": "^5.4.0". Here is the code snippet: d3.json('http://127.0.0.1:5000', function (err, data) { if (err) throw err; // Cre ...

Is it possible to turn off the differentiation between null and undefined in TypeScript strict null-checking mode?

I've been in the process of upgrading a large TypeScript codebase to enforce strict null-checks. This codebase contains numerous types with optional properties: interface MyInterface { member1?: number; member2?: string; } Additionally, it define ...

I encountered an issue where TypeScript does not recognize the type of a variable resulting from object destructuring

I'm attempting to utilize a variable from a destructuring expression as part of another object, but Typescript is not correctly recognizing its type. Here is an example of what I am trying to achieve: // defining a data structure type Data = { fir ...

Changing the Angular 5 ng-bootstrap Modal Dialog template dynamically in real-time

I'm currently developing a modal dialog that requires the ability to dynamically change the templateURL. The code shown is the default template, but I need to be able to swap it out dynamically. I'm unsure of how to achieve this, as the templateU ...

What is the process for setting up custom global interfaces in TypeScript using .d.ts files?

I'm currently facing an issue in my ReactJS project using Webpack2 and TypeScript. Everything is functioning perfectly except for one thing - I've been struggling to move my self-written interfaces into separate files so they are accessible throu ...

Unable to identify TypeScript version in Visual Studio Code, causing TS Intellisense to not function properly

Global Installation of TypeScript Below is what I see in my terminal when I run the command tsc --version. tsc --version // Version: 3.8.3 The TypeScript "version" is not showing up in the Status bar. When I try to select the TypeScript version fr ...

The Storybook compilation consistently encounters errors

Check out my repository here: https://github.com/zapify-ui/zapify I'm facing an issue with building Storybook using the command: npm run build-storybook How can I identify the specific error or debug it effectively? The error thrown is: (node:46619) ...

Enrich TypeScript objects by incorporating additional properties beyond the ones already present

If I have an expression and want to add extra properties without repeating existing ones, how can I achieve that? For instance, if the expression is a variable, it's simple to include additional fields (like adding field e): const x = { a: 1 }; cons ...

What is the process for enabling keyboard selections in a Material-UI Select component?

Is there a way to make the MUI Select component keyboard accessible by tabbing into it and using the first letter of the option to auto-select without opening the list? I am looking for a feature where pressing the initial letter selects the first item tha ...

Exploring Typescript: Combining types (rather than intersecting them)

Let's analyze the scenario below type MergeFn = <K1 extends string, V1, K2 extends string, V2>( k1: K1, v1: V1, k2: K2, v2: V2 ) => ??? let mergeFn: MergeFn // actual implementation doesn't matter for this question What should b ...

Jest is having difficulty locating a module while working with Next.js, resulting in

I am encountering some difficulties trying to make jest work in my nextjs application. Whenever I use the script "jest", the execution fails and I get the following result: FAIL __tests__/index.test.tsx ● Test suite failed to run ...

Understanding how to extract a specific value key from a JSON object in Typescript while utilizing Angular can greatly

I'm currently facing a challenge in Typescript with Angular where I need to retrieve a specific value from a JSON constant. While I am aware of the performance implications, I am wondering if there is a more efficient way to access this value within t ...

The assignment of Type Program[] to a string[] is not valid

I am working with a class that contains information about different programs. My goal is to filter out the active and inactive programs, and then retrieve the names of those programs as an array of strings. Below is the structure of the Program class: ex ...