Now that users can sign up, let's see how do send the token with all requests.
$ yarn remove apollo-boost
$ yarn add apollo-link-http apollo-link-context apollo-cache-inmemory graphql-tag
import ApolloClient from "apollo-boost";
const client = new ApolloClient({ uri: "/graphql" });
import ApolloClient from "apollo-client";
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
const httpLink = createHttpLink({
uri: '/graphql',
});
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const token = localStorage.getItem('token');
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
@Resolver(of => Health)
class HealthResolver {
@Query(returns => Health)
async health(@Ctx() context: GraphQLContext): Promise<Health> {
console.log({ context })
return { ok: 1 };
}
}
{
context: {
user: { id: '9cd7e02b-0333-4d67-a43b-6957fb38caac', iat: 1570621069 }
}
}