【发布时间】: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}`)
};
}
});
【问题讨论】: