프리즈마에서 트랜잭션 하는 방법은 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]);
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 };
});
jest로 트랜잭션 안의 각각의 쿼리들은 mock이 안됨 (아직 지원이 안되는 듯)
$transaction
자체 결과를 mock 해서 사용.
https://www.prisma.io/docs/concepts/components/prisma-client/transactions
https://dev.to/this-is-learning/its-prisma-time-transactions-ji5