Based upon our previous implementation(s) of a server it’s now time to write some client code.
- yarn add apollo-client
- yarn add apollo-cache-inmemory
- yarn add apollo-link-http
- yarn add graphql-tag
- yarn add isomorphic-fetch
- yarn add -D @types/isomorphic-fetch
Now let’s create a simple script entry (this extends the previous post’s scripts section)
"scripts": {
"build": "tsc",
"client": "node client.js"
}
Now let’s create the file client.ts which should look like this
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import gql from 'graphql-tag';
import fetch from 'isomorphic-fetch';
const cache = new InMemoryCache();
const link = new HttpLink({
uri: 'http://localhost:4000/',
fetch: fetch
})
const client = new ApolloClient({
cache,
link,
});
client.query({
query: gql`
{
users {
firstName
lastName
}
}`
})
.then((response: any) => console.log(response.data.users));
The response.data.users should now output the array of User objects.
Here’s an example of a mutation
client.mutate({
mutation: gql`
mutation {
create(user: {
firstName: "Miner",
lastName: "FortyNiner"
}) {
firstName
lastName
}
}
`
}).then((response: any) => console.log(response.data.create));
Note: I had lots of issues around the fetch code, with errors such as Invariant Violation:
fetch is not found globally and no fetcher passed, to fix pass a fetch for your environment like
https://www.npmjs.com/package/node-fetch.. The addition of the isomorphic-fetch solved this problem.