Search code examples
postgresqlprismaprisma-transaction

Prisma: how to write transaction where results from one query are used by another query


I'm working on a project with Next.js and Prisma. In one of my API routes, I have a three queries. The results of the first and second queries are used in the third query. I'd like to do all three operations as a transaction and then return the data from the first query in the response.

I'm familiar with using prisma.$transaction but I don't know how to write it in this case where results #1 and #2 are used by query #3. Here are the queries as they are written now. Thanks in advance!

const { boardId } = req.body
const { description, status, title } = req.body.task

const createTask = await prisma.task.create({
  data: {
    board: boardId,
    description,
    status,
    title
  }
})

const statusArray = await prisma.board.findUnique({
  where: {
    id: boardId
  },
  select: {
    [status]: true
  }
})

const updateBoardStatusArray = await prisma.board.update({
  where: {
    id: boardId
  },
  data: {
    [status]: {
      set: [...statusArray[status], createTask.id]
    }
  }
})

// return data from first query
res.status(201).json({task: createTask})


Solution

  • Here you go:

     const { boardId } = req.body;
      const { description, status, title } = req.body.task;
    
      const [createTask] = await prisma.$transaction(async (prisma) => {
        const createTask = await prisma.task.create({
          data: {
            board: boardId,
            description,
            status,
            title,
          },
        });
    
        const statusArray = await prisma.board.findUnique({
          where: {
            id: boardId,
          },
          select: {
            [status]: true,
          },
        });
    
        const updateBoardStatusArray = await prisma.board.update({
          where: {
            id: boardId,
          },
          data: {
            [status]: {
              set: [...statusArray[status], createTask.id],
            },
          },
        });
        
        return [createTask, statusArray, updateBoardStatusArray];
      });
    
      // return data from first query
      res.status(201).json({ task: createTask });

    You can learn more about Interactive Transaction here