简体   繁体   English

在角Apollo Graphql中访问变异结果

[英]Accessing Mutation Result in Angular Apollo Graphql

I am new to Graphql and I am using the Apollo client with Angular 7. 我是Graphql的新手,并且在Angular 7中使用了Apollo客户端。

I have a mutation in the server that I am using for authentication.This mutation generates returns an access token and a refresh token: 我用于身份验证的服务器中有一个突变,此突变生成返回访问令牌和刷新令牌:

@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
      }
    }
  `;
}

I am running this mutation in my sign-in component like this: 我在登录组件中运行此突变,如下所示:

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

Once I get the access token I will need to add it as header on my requests. 获得访问令牌后,需要在请求中将其添加为标头。

From what I read from the Apollo Client all results from queries and mutations are cached locally in the client. 根据我从Apollo客户端上读取的内容,所有查询和变异的结果都将本地缓存在客户端中。 But it is not clear to me how can I access them and add it to the apollo-link. 但是我不清楚如何访问它们并将其添加到阿波罗链接中。

To be more clear I would like to do this in my Graphql module: 更清楚地说,我想在我的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}`)
    };
  }
});

Even official docs of Apollo Client suggest you store this token as usually - to localStorage. 甚至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()
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM