Instagram-clone#5-Post

Seo·2020년 5월 31일
0

InastagramClone

목록 보기
5/15

edit post, delete post, see feed 기능을 구현해보자

Enum

graphql에서 enum을 사용할 수 있다.

enum ACTIONS{
    EDIT
    DELETE
}

type Mutation {
  editPost(
    ...
    action: ACTIONS
    ...
  ): Post!
}

resolver에서 사용할 때에는 enum type이 string으로 오게 된다.

const { action } = args;
if(action === "EDIT"){
  ...
} else if(action === "DELETE"){
  ...
}

Edit Post, Delete Post

edit은 post id값으로 찾아서 update진행하면 된다.

delete할 때 다른 model을 type으로 가진 필드가 있다면(relation) onDelete옵션을 사용하여 미리 type을 지정해주어야 한다.

https://v1.prisma.io/docs/1.34/datamodel-and-migrations/datamodel-MYSQL-knul/#the-@relation-directive

type User {
  id: ID! @id
  stories: [Story!]! @relation(name: "StoriesByUser", onDelete: CASCADE)
}

type Story {
  id: ID! @id
  text: String!
  author: User @relation(name: "StoriesByUser")
}
Mutation: {
  editPost: async (_, args, { request, isAuthenticated }) => {
    isAuthenticated(request);
    const { id, caption, location, action } = args;
    const { user } = request;
    const post = await prisma.$exists.post({ id, user: { id: user.id } });
    if (post) {
      if (action === EDIT) {
        return prisma.updatePost({
          data: { caption, location },
          where: { id },
        });
      } else if (action === DELETE) {
        return prisma.deletePost({ id });
      }
    } else {
      throw Error("You can't do that");
    }
  },
},

See Feed

가령 기존 사용하던 RDB를 이용하여 web app을 개발하는데 이와 같이 user가 있고, 그 user가 follow하는 사람들의 post를 가져오는 백엔드 api 기능을 만든다고 생각해보자.

  1. db에 해당하는 orm을 설정해야하고
  2. db와 통신을 해야되고
  3. db에 날릴 쿼리를 작성해야 하고
  4. db에서 result를 받아서 데이터를 validation하고
  5. result를 다시 data structure에 담아서
  6. select_one, select_many, where_in, where_not_in 등등... 하나하나 다 만들어주어야 할 때도 있고...

...
등등의 기능들을 기본적으로 만들어 주어야 한다.(번거롭고 귀찮기까지 하고 디버깅도 힘들 수 있다.)
orm이나 기타 lib이 발전하면서 더 나은 개발환경이 되었지만, 그럼에도 불구하고 귀찮다.

그러나 prisma를 이용할 때는 제공된 기능들로 간단하게 만들 수 있다.
0. prisma 모델링을 작성하고,
1. prisma develop, generate를 한 뒤에
2. resolver는 prisma에서 제공된 기능들로 간단하게 구현 가능하다.

Query: {
  seeFeed: async (_, __, { request, isAuthenticated }) => {
    isAuthenticated(request);
    const { user } = request;
    const following = await prisma.user({ id: user.id }).following();
    return prisma.posts({
      where: {
        user: {
          id_in: [...following.map((user) => user.id), user.id],
        },
      },
      orderBy: "createdAt_DESC",
    });
  },
},

remind

prisma에서 제공하는 여러 기본적인 기능들(updatePost, deletePost...등)로 인해서 매우 간편하게 할 수 있다는 걸 다시 한 번 깨달았다.
한편으로는 좀 더 복잡하고 깊은 biz일 경우에도 제공된 기능들로만 사용하면서 더 간편하게 사용가능할까하는 생각이 들긴 하는데 일반적인 기능들 구현할 때는 충분하다고 보인다.

profile
개발관심자

0개의 댓글