GraphQLの理解のため、まずはライブラリなど使わずfetchでGraphQLのクエリを発行してみる。
const query = gql`{ books { id } }`; async function queryByFetch() { const res = await fetch('http://localhost:4000/graphql', { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query, }) }); if (!res.ok) { throw new Error(); } const result = await res.json() as any; if (!('data' in result)) { throw new Error(); } const { data } = result; console.log({ data }); } void queryByFetch();
できたので、ApolloClientを使ってみる。node上で使うなら、@apollo/client/coreからインポートが必要なよう。
import { ApolloClient, InMemoryCache, gql } from '@apollo/client/core'; const query = gql`{ books { id } }`; async function queryByClient() { const client = new ApolloClient({ uri: 'http://localhost:4000/', cache: new InMemoryCache(), }); const result = await client.query({ query }); if (!('data' in result)) { throw new Error(); } const { data } = result; console.log({ data }); } void queryByClient();