prisma transaction

00_8_3·2022년 7월 19일
0

Migration To Prisma

목록 보기
4/11

트랜잭션

프리즈마에서 트랜잭션 하는 방법은 2가지가 있다고 합니다.

하나는 공식적인 방법
나머지는 preview 기능입니다.

공식적인 방법

const result = await prisma.$transaction([
  prisma.author.create({
    data: {
      firstName: "Author from transaction",
      lastName: "Author from transaction",
      age: getRandomInt(16, 100),
    },
  }),
  prisma.post.create({
    data: {
      title: "Post from transaction",
      content: "Post from transaction",
      published: false,
    },
  }),
]);

// 또는 아래와 같이

const author = prisma.author.create({
    data: {
      firstName: "Author from transaction",
      lastName: "Author from transaction",
      age: getRandomInt(16, 100),
    },
  });
  const post = prisma.post.create({
    data: {
      title: "Post from transaction",
      content: "Post from transaction",
      published: false,
    },
  }),

const result = await prisma.$transaction([author, post]);

Preview 방법

generator client {
  provider = "prisma-client-js"
  previewFeatures = ["interactiveTransactions"] //이것을 추가
}
const result = await prisma.$transaction(async () => {
  const authorData = {
    firstName: "Author from transaction",
    lastName: "Author from transaction",
    age: getRandomInt(16, 100),
  } as const;
  const author = await prisma.author.create({
    data: authorData,
  });
  const post = await prisma.post.create({
    data: {
      title: "Post from transaction",
      content: "Post from transaction",
      published: false,
      authors: {
        create: [
          {
            authorId: author.id,
          },
        ],
      },
    },
    include: {
      authors: {
        include: {
          author: true,
        },
      },
    },
  });
  return { author, post };
});

prisma transaction with jest

jest로 트랜잭션 안의 각각의 쿼리들은 mock이 안됨 (아직 지원이 안되는 듯)

$transaction 자체 결과를 mock 해서 사용.

추가

  • preview 기능이 정식 채택되었다.
  • 2023-02-19에 작성.

참고

https://www.prisma.io/docs/concepts/components/prisma-client/transactions

https://dev.to/this-is-learning/its-prisma-time-transactions-ji5

0개의 댓글