34日目

10455 ワード

https://domain.gabia.com/regist/today_domain
https://cloud.google.com/free
graphql vs REST-API
既存REST-API
READ
axios.get(APIアドレス)
put, post, delete

graphqlは端点のREST-APIで、POST方式がよく使われています

{
"query": "mutation createBoard { createBoard(createBoardInput: {writer: 철수 , password: 1234 , title: 제목 , contents: 내용 }) {_id, title, write, contents}}"
}
optimistic ui

1.ワークロードの少ないAPI
2.99%以上の成功API
3.失敗しても損はないAPI
import { gql, useMutation, useQuery } from "@apollo/client";
import {
  IMutation,
  IMutationLikeBoardArgs,
  IQuery,
  IQueryFetchBoardArgs,
} from "../../src/commons/types/generated/types";

const FETCH_BOARD = gql`
  query fetchBoard($boardId: ID!) {
    fetchBoard(boardId: $boardId) {
      likeCount
    }
  }
`;
const FETCH_LIKE = gql`
  mutation likeBoard($boardId: ID!) {
    likeBoard(boardId: $boardId)
  }
`;

const OptimisticUIPage = () => {
  const [fetchLike] = useMutation<
    Pick<IMutation, "likeBoard">,
    IMutationLikeBoardArgs
  >(FETCH_LIKE);
  const { data } = useQuery<Pick<IQuery, "fetchBoard">, IQueryFetchBoardArgs>(
    FETCH_BOARD,
    { variables: { boardId: "61b816aa717be5002baa70a8" } }
  );

  const onClicklike = () => {
    fetchLike({
      variables: { boardId: "61b816aa717be5002baa70a8" },
      optimisticResponse: {
        likeBoard: (data?.fetchBoard.likeCount || 0) + 1,
      },
      update(cache, { data }) {
        cache.writeQuery({
          query: FETCH_BOARD,
          variables: { boardId: "61b816aa717be5002baa70a8" },
          data: {
            fetchBoard: {
              _id: "61b816aa717be5002baa70a8",
              _typename: "Board",
              likeCount: data?.likeBoard,
            },
          },
        });
      },
    });
    // refetch({ boardId: "61b816aa717be5002baa70a8" });
  };

  return (
    <>
      <div>좋아요 갯수: {data?.fetchBoard.likeCount}</div>
      <button onClick={onClicklike}>좋아요</button>
    </>
  );
};

export default OptimisticUIPage;