0

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

Neil Girardi
  • 4,533
  • 1
  • 28
  • 45

1 Answers1

2

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

Hoàng Huy Khánh
  • 1,071
  • 8
  • 16
  • Ah, I see! It's very simple. I have one more question. The value that I want to return in `res.json()` is the result of `createTask`. But it appears I cannot simply return a value, I have to return a query otherwise I get error promises.map is not a function. How can I do that? – Neil Girardi Oct 04 '22 at 02:24
  • I know how to do it, but you should update the question first then I will edit my answer too. – Hoàng Huy Khánh Oct 04 '22 at 02:44
  • 1
    Ok, I updated my answer too. Hope it help! – Hoàng Huy Khánh Oct 04 '22 at 14:41