**22. computed Field( Photo, Hashtag)(1)** very important

김종민·2022년 4월 25일
0

insta-backend

목록 보기
21/37

DB에는 없지만, graphql상에서는 존재, DB는 터치하지 않고, data를 manage함.

photos.typeDefs.js

import { gql } from 'apollo-server'

export default gql`
  type Photo {
    id: Int!
    user: User!
    file: String!
    caption: String
    hashtags: [Hashtag]
    createdAt: String!
    updatedAt: String!
    likes: Int!
  }
  type Hashtag {
    id: Int!
    hashtag: String!
    photos(page: Int!): [Photo]
    totalPhotos: Int!
    createdAt: String!
    updatedAt: String!
  }
  type Like {
    id: Int!
    photo: Photo!
    createdAt: String!
    updatedAt: String!
  }
`

2. photos.resolvers.js

import prisma from '../client'

export default {
  Photo: {
  ///Photo의 computed field
    user: ({ userId }) => prisma.user.findUnique({ where: { id: userId } }),
    ///parent자리, 혹은 root자리에 userId를 넣어서, photo의 user를 찾음.
    
    hashtags: ({ id }) =>
    ///id는 photo의 id임.
    
      prisma.hashtag.findMany({
        where: {
          photos: { some: { id } },
        },
      }),
    //// hashtag의 DB중 photos중에서 위의 photo id 가 들어있는 hashtag를 찾음 
      
    likes: ({ id }) => prisma.like.count({ where: { photoId: id } }),
    ///photo id를 parent혹은 root 자리에 넣어서
    ///그 photo의 like갯수를 count함.
  },
  Hashtag: {
  ///Hashtag의 computed Field
    photos: ({ id }, { page }) => {
      return prisma.hashtag.findUnique({ where: { id } }).photos()
    },
    ///hashtag의 id를 입력받아서 그 hashtag를 가진 photo들을 return해줌.
    
    totalPhotos: ({ id }) =>
    ///id는 hashtag의 id를 뜻함.
    
      prisma.photo.count({
        where: {
          hashtags: {
            some: { id },
          },
        },
      }),
      ////hashtag의 id(#orange)를 가진 photo를 찾아서 count해서 return해줌,
  },
}
profile
코딩하는초딩쌤