在角Apollo Graphql中访问变异结果

时间:2019-01-17 15:33:20

标签: graphql apollo

我是Graphql的新手,并且正在Angular 7中使用Apollo客户端。

我在用于身份验证的服务器中有一个突变。此突变生成返回访问令牌和刷新令牌:

@Injectable({
  providedIn: "root"
})
export class LoginTokenAuthGQL extends Apollo.Mutation<
  LoginTokenAuth.Mutation,
  LoginTokenAuth.Variables
> {
  document: any = gql`
    mutation loginTokenAuth($input: LoginAuthInput!) {
      loginTokenAuth(input: $input) {
        accessToken
        refreshToken
      }
    }
  `;
}

我正在这样在我的登录组件中运行此突变:

 onLoginSubmit() {
    const email = this.loginForm.controls['userEmail'].value;
    const password = this.loginForm.controls['userPassword'].value;

    console.log('Sending mutation with', email, password);

    this.loginGQL.mutate({
      input: {
        email,
        password,
        userType: AuthUserType.Crm
      }
    }).pipe(
      map((response) => response.data )
    ).subscribe(
      (output: LoginTokenAuth.Mutation) => {
        console.log('Access token', output.loginTokenAuth.accessToken);
        console.log('Refresh token', output.loginTokenAuth.refreshToken);

        console.log(this.apollo.getClient().cache);
      },
      ((error: any) => {
        console.error(error);
      })
    );
  }

一旦获得访问令牌,就需要在请求中将其添加为标头。

根据我从Apollo客户端上读取的内容,所有查询和变异的结果都被本地缓存在客户端中。但是我不清楚如何访问它们并将其添加到阿波罗链接。

更清楚地说,我想在我的Graphql模块中这样做:

const http = httpLink.create({uri: '/graphql'});

const auth = setContext((_, { headers }) => {

  // get the authentication token from the cache
  const token = ???

  if (!token) {
    return {};
  } else {
    return {
      headers: headers.append('Authorization', `Bearer ${token}`)
    };
  }
});

1 个答案:

答案 0 :(得分:0)

甚至official docs of Apollo Client也建议您像往常一样将此令牌存储在localStorage中。

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()
});