Skip to content

Instantly share code, notes, and snippets.

@MauricioAires
Last active March 27, 2023 13:37
Show Gist options
  • Save MauricioAires/b549efc6cf0be473e02bff540446cf56 to your computer and use it in GitHub Desktop.
Save MauricioAires/b549efc6cf0be473e02bff540446cf56 to your computer and use it in GitHub Desktop.

GRAPHQL + FETCH

Consumir uma api graphql utilizando apenas fetch

// IIFE - This is just to user snippets on chrome and
// make sure we won't have an error like:
// Uncaught SyntaxError: Identifier 'createPost'
// has already been declared
(async () => {
  console.clear();

  const createPost = async (variables) => {
    const graphQLUrl = 'http://localhost:4003/';
    const query = `
          mutation CREATE_POST(
            $title: String!
            $body: String!
            $userId: String!
          ) {
            createPost(
              data: {
                title: $title
                body: $body
                userId: $userId
              }
            ) {
              id
              title
              body
              user {
                firstName
              }
              indexRef
              createdAt
            }
          }
      `;
    const response = await fetch(graphQLUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        query,
        variables,
      }),
    });

    const post = await response.json();

    return post;
  };

  const post1 = await createPost({
    title: 'title 1',
    body: 'body 1',
    userId: '602',
  });

  const post2 = await createPost({
    title: 'title 2',
    body: 'body 2',
    userId: '',
  });

  console.log(post1);
  console.log(post2);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment