graphql-fragment-mask

Mask GraphQL query result with Fragment

Usage no npm install needed!

<script type="module">
  import graphqlFragmentMask from 'https://cdn.skypack.dev/graphql-fragment-mask';
</script>

README

graphql-fragment-mask

CI Coverage Status npm LICENSE

Mask GraphQL query result with Fragment (graphql-anywhere alternative).

Usage

import gql from "graphql-tag";
// Import generated types and generated `TypedDocumentNode` objects of the fragment.
import { PostHeaderFragmentDoc, GetPostDocument } from "./__generated__/Post.generated";

const _POST_HEADER = gql`
  fragment PostHeader on Post {
    title
    author {
      fullName
      avatarUrl
    }
  }
`;

const _GET_GREETING = gql`
  query GetPost($postId: !String) {
    postById(postId: $postId) {
      ...PostHeader
      // and more fields...
    }
  }
`;

const [data] = useQuery(GetPostDocument, { variables: { postId: "123" } });


// Use typed document node generated by `@graphql-codegen/typed-document-node` (RECOMMENDED).
const header = maskWithFragment(PostHeaderFragmentDoc, data.postById);
// {
//   __typename: "Post",
//   title: "Hello, GraphQL!",
//   author: {
//     __typename: "User",
//     fullName: "Masayuki Izumi",
//     avatarUrl: "https://example.com/users/izumin5210/avatar",
//   }
// }

// Alternatively, you can use the document node defined by `graphql-tag`.
// const header = maskWithFragment(_POST_HEADER, data.postById);

Dependencies

Install this library with graphql-js.

yarn add graphql graphql-fragment-mask

If you want to use it with TypedDocumentNode, setup TypedDocumentNode plugin with graphql-code-generator (RECOMMENDED, please refer TypedDocumentNode's instruction).

yarn add --dev \
  @graphql-codegen/cli \
  @graphql-codegen/typescript \
  @graphql-codegen/typescript-operations \
  @graphql-codegen/typed-document-node
yarn add @graphql-typed-document-node/core