카테고리 없음

[Prisma] createMany시 생성 된 data 반환하기

minseok__ 2023. 8. 16. 11:30

기본적으로 Prisma에서는 createMany시 몇 개의 row가 생성되었는지 개수를 반환합니다.

 

 

예를 들어 아래와 같은 코드가 있다고 가정해봅시다. 

 

  public async createPosts(authorId: number) {
    return this.prisma.post.createMany({
      data: [
        {
          title: 'Post 1',
          content: 'Content 1',
          authorId,
        },
        {
          title: 'Post 2',
          content: 'Content 2',
          authorId,
        },
      ],
    });
  }

 

 

위와 같다면 실제로 반환 되는 데이터는 아래와 같습니다. 

 

{
    "count": 2
}

 

 

하지만 원하는 반환 값이 실제 생성된 data라면 별도로 Prisma 내장 메서드와 같은 것으로는 이 부분을 해결할 수는 없습니다. (별 다른 옵션이 없다는 뜻)

 

따라서, response body에 실제 생성된 data를 반환하고 싶다면 적당한 방법으로 우회해야합니다.

 

 

아래와 같이 말이죠!

 

  public createPosts(authorId: number) {
    const postCreationPromises = [
      {
        title: 'Post 1',
        content: 'Content 1',
        authorId,
      },
      {
        title: 'Post 2',
        content: 'Content 2',
        authorId,
      },
    ].map((postData) => this.prisma.post.create({ data: postData }));

    return this.prisma.$transaction(postCreationPromises);
  }

createPosts 함수 내에서 create 메서드를 사용하면서 $transaction을 이용하여 모든 생성 작업을 하나의 트랜잭션으로 묶으면

우리가 원하는 대로 반환 됩니다!

 

 

[
    {
        "pid": 5,
        "title": "Post 1",
        "content": "Content 1",
        "createdAt": "2023-08-16T02:28:31.064Z",
        "updatedAt": "2023-08-16T02:28:31.064Z",
        "authorId": 1
    },
    {
        "pid": 6,
        "title": "Post 2",
        "content": "Content 2",
        "createdAt": "2023-08-16T02:28:31.064Z",
        "updatedAt": "2023-08-16T02:28:31.064Z",
        "authorId": 1
    }
]

 

위와 같이 반환되는 것을 알 수 있습니다.

 

 

출처: https://github.com/prisma/prisma/issues/8131#issuecomment-997667070

 

`createMany` should return the created records · Issue #8131 · prisma/prisma

Initially brought up here: #4998 (comment) Problem The fact that the createMany API does not return the created records (which should be possible for Postgres) makes it difficult/impossible to use ...

github.com