【问题标题】:Accessing Mutation Result in Angular Apollo Graphql在 Angular Apollo Graphql 中访问突变结果
【发布时间】:2019-06-11 20:20:50
【问题描述】:

我是 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 客户端读取的所有查询和突变结果都缓存在客户端本地。但我不清楚如何访问它们并将其添加到 apollo-link。

为了更清楚,我想在我的 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}`)
    };
  }
});

【问题讨论】:

    标签: graphql apollo


    【解决方案1】:

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

    【讨论】:

    • 好吧,根据 Auth0 我应该将令牌仅存储在内存中或将其添加到 cookie:auth0.com/docs/security/store-tokens。如果我想将它存储在内存中,我想我必须手动将它添加到我的本地状态。这样我以后可以查询。但是我不确定这是否不是一个好习惯。
    猜你喜欢
    • 2020-07-15
    • 2020-04-24
    • 2020-05-29
    • 2019-11-27
    • 2021-08-22
    • 1970-01-01
    • 2019-09-23
    • 2017-02-07
    • 2021-04-24
    相关资源
    最近更新 更多