TIL # 123: [Prisma ORM] nested SELECT(Error Solved!)

셀레스틴 허·2021년 5월 12일
0
post-thumbnail

상황설명: 급하게 구현한 API를 하나씩 뜯어 고치고 있다.

코드 기능 설명...

  • 여러 service layer 중 하나 -> user를 다룸
  • user가 예약한 reservation 내역 하나 불러옴

이전 코드의 문제점:

user_id...program_id...program_status_id처럼 id값만 "띡" 보냈다...
장고가 편하지 그래... django orm은 최고야...


이전 코드

UserService.js

const getOneReservation = ({ reservation_id }) => {
    return prisma.reservations.findUnique({
        where: {
            id: reservation_id,
        },
    })
}

Postman Response

{
    "reservation": {
        "id": 1,
        "program_id": 1,
        "user_id": 2,
        "created_at": "2021-04-26T01:27:32.000Z",
        "updated_at": null,
        "deleted_at": null,
        "reservation_number": "RV6039755034",
        "program_status_id": 1,
        "person_count": 1
    }
}

저렇게 id값만 보내는 곳은 없다...🥲

고치기

prisma orm 공식문서 에 나와있는 예제 참고해서 고쳐봤다.

prisma orm 공식문서 예제)

const getUser = await prisma.user.findUnique({
  where: {
    id: 19,
  },
  select: {
    // This will work!
    email: true,
    posts: {
      select: {
        title: true,
      },
    },
  },
})

이중 SELECT문으로 필요한 정보값을 가져와보자!!


이중 SELECT문 적용 후 코드

UserService.js

const getOneReservation = ({ reservation_id }) => {
    return prisma.reservations.findUnique({
        where: {
            id: reservation_id,
        }, 
        select: { 
            id: true,
            updated_at: true,
            deleted_at: true,
            reservation_number: true,
            program_statuses: {
                select: {
                    status: true,
                },
            },
            person_count: true,
            programs: {
                select: {
                    name: true,
                    description: true,
                    start_point_id: true,
                    end_point_id: true,
                    total_count: true,
                    achieved_count: true,
                    run_date: true,
                    reservation_closing_date: true,
                    start_time: true,
                    end_time: true,
                    is_full: true,
                    hosts: {
                        select: {
                            id: true,
                            name: true,
                            description: true,
                            program_count: true,
                        }
                    },
                },
            },
        },
    })
}

이제 id값이 아닌 실질적인 웹사이트 구현에 필요한 정보를 보낼 수있다!

Reference:
https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries

profile
Software Developer / 고통은 필연, 괴로움은 선택

0개의 댓글