Part4: Apollo Client로 구독 서비스 GUI 만들기

송톰톰·2023년 1월 27일
0
post-thumbnail

스키마, 리졸버 수정

UUID 자동생성하는 방식에서 사용자의 입력값을 받도록 GraphQL 스키마, 리졸버를 수정합니다.

  • schema.graphqls
input CreatePostInput{ # 추가
    id: ID!
}

type Mutation {
    createPost(input: CreatePostInput!):Post! # 수정
    createComment(input: CreateCommentInput!): Comment!
}
  • schema.resolvers.go
// CreatePost is the resolver for the createPost field.
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*model.Post, error) {
	_, cancel := context.WithTimeout(ctx, 3*time.Second)
	defer cancel()

	post := model.Post{
		ID: input.ID, // 수정
	}
	r.DB.Create(post)

	return &post, nil
}

클라이언트 GraphQL 정의

다음 Post, Comment 관련 Mutation, Query GraphQL 을 정의합니다.

const CREATE_POST = gql`
  mutation CreatePost($input: CreatePostInput!) {
    createPost(input: $input) {
      id
    }
  }
`;

const CREATE_COMMENT = gql`
  mutation CreateComment($input: CreateCommentInput!) {
    createComment(input: $input) {
      id
      postId
      content
    }
  }
`;

const LIST_COMMENTS = gql`
  query ListComments($where: CommentsWhere!) {
    comments(where: $where) {
      id
      postId
      content
    }
  }
`;

Hooks 개발

다음 useState 코드를 입력합니다.

  const [id, setId] = useState<string>('songtomtom');
  const [content, setContent] = useState<string>('Hello~!');

다음 useMutation, useQuery 정의합니다.

  const [createPost] = useMutation(CREATE_POST, {
    variables: { input: { id } },
  });

  const [createComment] = useMutation(CREATE_COMMENT, {
    variables: { input: { postId: id, content } },
  });

  const { data, loading } = useQuery(LIST_COMMENTS, {
    variables: { where: { postId: id } },
  });

<input>, <button> 태그 onClick, onChange Callback 함수를 입력합니다.

  const onClickCreatePost = async () => {
    const { data } = await createPost();
    if (data) {
      // Do something
    }
  };

  const onClickCreateComment = async () => {
    const { data } = await createComment();
    if (data) {
      // Do something
    }
  };

  const onChangeId = (e: ChangeEvent<HTMLInputElement>) => {
    setId(e.target.value);
  };

  const onChangeContent = (e: ChangeEvent<HTMLInputElement>) => {
    setContent(e.target.value);
  };

JSX 작성

Hooks 에서 정의한 State, Callback 함수를 입력합니다.

return (
    <div>
      <div>
        <input type="text" onChange={onChangeId} value={id} />
        id
        <br />
        <input type="text" onChange={onChangeContent} value={content} />
        content
      </div>

      <button onClick={onClickCreatePost}>create post</button>
      <button onClick={onClickCreateComment}>create comment</button>
      <ul>
        {!loading &&
          data.comments.map((item: any, index: number) => {
            return (
              <li key={index}>
                <small>{item.postId}</small>: <strong>{item.content}</strong>
              </li>
            );
          })}
      </ul>
    </div>
  );

GraphQL 테스트

정상 동작 하는지 확인합니다.

Reference

Github

0개의 댓글