15. Upload Photo

김종민·2022년 4월 25일
0

insta-backend

목록 보기
14/37

1. uploadPhoto.typeDefs.js

import { gql } from 'apollo-server'

export default gql`
  type Mutation {
    uploadPhoto(file: String!, caption: String): Photo
  }
`

별거 없음.. file은 나중에 S3에 사진 올리고url을 반환받을 예정.
caption은 사진에 대한 설명.
return은 일단 Photo인데, 나중에 바뀔 수 있음.

2. uploadPhoto.resolvers.js

import prisma from '../../client'
import { protectedResolver } from '../../users/users.util'

export default {
  Mutation: {
    uploadPhoto: protectedResolver(
      async (_, { file, caption }, { loggedInUser }) => {
        let hashtagObj = []
        if (caption) {
          const hashtags = caption.match(/#[\w]+/g)
          hashtagObj = hashtags.map((hashtag) => ({
            where: { hashtag },
            create: { hashtag },
          }))
          /////caption에서 hashtag를 뽑아내어서 hashtags에 담아줌.
          ////hashtagObj는 caption에서 뽑아낸 hashtag를 map으로 where와 create에 담아줌.
          ////where와 create는 connectOrCreate의 변수로 
          ////hashtag가 존재하면 where에 결합되고  hashtag가 없으면 새로 만들어짐.  매우 중요함...
          
          
          console.log(hashtagObj)
        }
        return prisma.photo.create({
        ///일단은 photo를 return함.
        
          data: {
            file,
            caption,
            user: {
              connect: {
                id: loggedInUser.id,
              },
              ////user를 연결해줌.!!!!
              
            },
            ...(hashtagObj.length > 0 && {
              hashtags: {
                connectOrCreate: hashtagObj,
              },
            }),
            /////hashtagObj의 갯수가 1개이상이면,
            ////photo의 hashtags에 hashtagObj를 연결해줌.
            
          },
        })
      }
    ),
  },
}

checkPoint!!
1. caption에서 hashtag를 뽑아내는방법
( I love #orange #apple and #baseball) ===> #orange #apple #baseball

  1. photo의 hashtags에 hashtag를 담기 위해서 connectOrCreate를 사용
    where, create 사용 중요함!! 명심할 것.
profile
코딩하는초딩쌤

0개의 댓글