graphql-tag: how to get the actual string for the body request?
Asked Answered
R

2

7

I want to use the library https://github.com/apollographql/graphql-tag I'm looking for someone smarter than me that understands how to actually use it.

Say I have a GraphQL query document like so:

const query = gql`
  {
    user(id: 5) {
      ...User_user
    }
  }
  ${userFragment}
`

How do I get now the string to add in the http body request? I end up with an object, which allows me to do some introspection and manipulations, great, but how to get the actual body string for the server request?

I'm missing something obvious I guess...

Rolland answered 5/3, 2022 at 11:54 Comment(0)
N
5

to answer the original question:

How do I get now the string to add in the http body request?

Assuming as in the example above you already parsed to an AST, for reasons such as using fragments (or for other reasons, see https://github.com/apollographql/graphql-tag#why-use-this)

In that case, you can parse the AST to string using graphql's print helper function, along these lines:

import gql from 'graphql-tag';
import { print } from 'graphql/language/printer';

const AST = gql`
  {
    user(id: 5) {
      ...User_user
    }
  }
  ${userFragment}
`
const query = print(AST);
Nahshon answered 21/11, 2022 at 13:46 Comment(0)
S
3

The object you get by applying qql to your graphql query code is the AST (abstract syntax tree) for the graphql. This AST is normally used with the apollo-client to execute requests. However, you can use any other library that is capable of executing GraphQL requests using AST.

Assuming you are willing to use Apollo, here's an example on their website how it works (https://www.apollographql.com/docs/react/data/queries).

import { gql, useQuery } from '@apollo/client';

const GET_DOGS = gql`
  query GetDogs {
    dogs {
      id
      breed
    }
  }
`;

function Dogs({ onDogSelected }) {
  const { loading, error, data } = useQuery(GET_DOGS);

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  return (
    <select name='dog' onChange={onDogSelected}>
      {data.dogs.map((dog) => (
        <option key={dog.id} value={dog.breed}>
          {dog.breed}
        </option>
      ))}
    </select>
  );
}

This example is for React with hooks (this is a primary way to use Apollo). If you still want to use Apollo but don't use React then you could use bare ApolloClient and still use your AST to run queries. See the link below to learn how to use ApolloClient directly.

https://www.apollographql.com/docs/react/api/core/ApolloClient/

Finally, if you are not willing to bother with Apollo and/or AST, you can simply execute the query directly. In this case, you don't need to use gql and parse it into AST. See a simplified but working example below.

const query = `
query($id: Int!) {
    user(id: $id) {
        id
        login
        email
    }
}
`;

const variables = {
    id: 5
};

const result = await fetch("http://your-graphql-backend.tld", {
    method: "POST",
    body: JSON.stringify({
        query,
        variables,
    }),
    headers: {
        "content-type": "application/json",
    }
});

Note: The implementation above (especially the query part) depends on your GraphQL schema and backend implementation. It may differ, but in principle, this should work with most modern graphql backends.

Stravinsky answered 8/6, 2022 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.