18. editPhoto

김종민·2022년 4월 25일
0

insta-backend

목록 보기
17/37

1. editPhoto.typeDefs.js

import { gql } from 'apollo-server'

export default gql`
  type EditPhotoResult {
    ok: Boolean!
    error: String
  }
  type Mutation {
    editPhoto(id: Int!, caption: String!): EditPhotoResult!
  }
`

2. editPhoto.resolvers.js

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

export default {
  Mutation: {
    editPhoto: protectedResolver(
      async (_, { id, caption }, { loggedInUser }) => {
        const oldPhoto = await prisma.photo.findFirst({
          where: {
            id,
            userId: loggedInUser.id,
          },
          ///photo의 id와 그 photo의 userId로 edit할려는 photo를 찾음.
          
          include: {
            hashtags: {
              select: {
                hashtag: true,
              },
            },
          },
          ///include는 찾은 photo에 hashtags를 추가로 붙여서 data를 반환해줌.
        })
        if (!oldPhoto) {
          return {
            ok: false,
            error: 'Photo not found',
          }
        }
        await prisma.photo.update({
          where: { id },
          data: {
            caption,
            hashtags: {
              disconnect: oldPhoto.hashtags,
              connectOrCreate: processHashtags(caption),
            },
          },
        })
        ///기존에 edit할려는 photo의 hashtags들을 disconnect해주고
        ///새로운 caption의 hashtags들을 photo에 update해줌,
        ///processHashtags component를 만들어서 caption의 hashtag를 뽑아줌.
        
        return {
          ok: true,
        }
      }
    ),
  },
}

3. photos.util.js

export const processHashtags = (caption) => {
  const hashtags = caption.match(/#[\w]+/g) || []
  return hashtags.map((hashtag) => ({
    where: { hashtag },
    create: { hashtag },
  }))
}

caption에서 hashtag를 뽑아내서 createOrCreate에 바로 넣어줄 수 있는 component

profile
코딩하는초딩쌤

0개의 댓글