![](/img/trans.png)
[英]How to create a graphql query with arguments in angular using apollo client library
[英]refresh token for angular using graphql and apollo client
我正在嘗試設置刷新令牌策略以在我的第一個請求返回 401 時使用 GraphQL 和阿波羅客戶端刷新 angular 9 中的 JWT。
我已經為 graphql 設置了一個新的 angular 模塊,我正在創建我的 apolloclient。 即使使用經過身份驗證的請求,一切都很好,但我需要讓我的正常刷新令牌策略也能正常工作(刷新令牌周期完成后重新制作並返回原始請求)。 我只找到了一些資源來幫助解決這個問題,而且我已經非常接近了——我唯一缺少的是從我的刷新令牌 observable 中返回 observable。
這是認為應該工作的代碼:
import { NgModule } from '@angular/core';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { AuthenticationService } from './authentication/services/authentication.service';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { onError } from 'apollo-link-error';
export function createApollo(httpLink: HttpLink, authenticationService: AuthenticationService) {
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
Authorization: 'Bearer ' + localStorage.getItem('auth_token')
}
});
return forward(operation);
});
const errorLink = onError(({ forward, graphQLErrors, networkError, operation }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
{
if (message.toLowerCase() === 'unauthorized') {
authenticationService.refreshToken().subscribe(() => {
return forward(operation);
});
}
}
);
}
});
return {
link: errorLink.concat(authLink.concat(httpLink.create({ uri: 'http://localhost:3000/graphql' }))),
cache: new InMemoryCache(),
};
}
@NgModule({
exports: [ApolloModule, HttpLinkModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, AuthenticationService]
}
]
})
export class GraphqlModule { }
我知道我的請求第二次起作用了,因為如果我從我的 authenticationService 訂閱中的 forward(operation) observable 中注銷結果,我可以在最初的 401 失敗后看到結果。
if (message.toLowerCase() === 'unauthorized') {
authenticationService.refreshToken().subscribe(() => {
return forward(operation).subscribe(result => {
console.log(result);
});
});
}
上面顯示了來自原始請求的數據,但它沒有傳遞給我最初稱為 graphql 的組件。
我遠不是可觀察的專家,但我認為我需要做某種 map(平面圖、合並圖等)以使此返回正常工作,但我只是不知道。
任何幫助將不勝感激
TIA
編輯#1:這讓我更接近了,因為它現在實際上訂閱了我在 AuthenticationService 中的方法(我在 tap() 中看到了結果)
const errorLink = onError(({ forward, graphQLErrors, networkError, operation }) => {
if (graphQLErrors) {
if (graphQLErrors[0].message.toLowerCase() === 'unauthorized') {
return authenticationService.refreshToken()
.pipe(
switchMap(() => forward(operation))
);
}
}
});
我現在看到這個錯誤被拋出:
core.js:6210 錯誤類型錯誤:您提供了一個無效的 object,其中預期為 stream。 您可以提供 Observable、Promise、Array 或 Iterable。
編輯#2:包括 onError() function 簽名的截圖:
編輯#3 這是最終的工作解決方案,以防其他人遇到此問題並需要它用於 angular。 我不喜歡更新我的服務方法來返回 promise,然后將 promise 轉換為 Observable - 但正如 @Andrei Gătej 為我發現的那樣,這個 Observable 來自不同的命名空間。
import { NgModule } from '@angular/core';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { AuthenticationService } from './authentication/services/authentication.service';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { onError } from 'apollo-link-error';
import { Observable } from 'apollo-link';
export function createApollo(httpLink: HttpLink, authenticationService: AuthenticationService) {
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
Authorization: 'Bearer ' + localStorage.getItem('auth_token')
}
});
return forward(operation);
});
const errorLink = onError(({ forward, graphQLErrors, networkError, operation }) => {
if (graphQLErrors) {
if (graphQLErrors.some(x => x.message.toLowerCase() === 'unauthorized')) {
return promiseToObservable(authenticationService.refreshToken().toPromise()).flatMap(() => forward(operation));
}
}
});
return {
link: errorLink.concat(authLink.concat(httpLink.create({ uri: '/graphql' }))),
cache: new InMemoryCache(),
};
}
const promiseToObservable = (promise: Promise<any>) =>
new Observable((subscriber: any) => {
promise.then(
value => {
if (subscriber.closed) {
return;
}
subscriber.next(value);
subscriber.complete();
},
err => subscriber.error(err)
);
});
@NgModule({
exports: [ApolloModule, HttpLinkModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, AuthenticationService]
}
]
})
export class GraphqlModule { }
我對 GraphQL 不太熟悉,但我認為這應該可以正常工作:
if (message.toLowerCase() === 'unauthorized') {
return authenticationService.refreshToken()
.pipe(
switchMap(() => forward(operation))
);
}
此外,如果您想了解mergeMap
(和concatMap
)如何工作,您可以查看這個答案。
switchMap
只保留一個活動的內部 observable,一旦外部值進入,當前的內部 observable 將被取消訂閱,並根據新到達的外部值和提供的 function 創建一個新的內部 observable。
這是我為將來看到這個的人的實現
Garaphql 模塊:
import { NgModule } from '@angular/core';
import { APOLLO_OPTIONS } from 'apollo-angular';
import {
ApolloClientOptions,
InMemoryCache,
ApolloLink,
} from '@apollo/client/core';
import { HttpLink } from 'apollo-angular/http';
import { environment } from '../environments/environment';
import { UserService } from './shared/services/user.service';
import { onError } from '@apollo/client/link/error';
import { switchMap } from 'rxjs/operators';
const uri = environment.apiUrl;
let isRefreshToken = false;
let unHandledError = false;
export function createApollo(
httpLink: HttpLink,
userService: UserService
): ApolloClientOptions<any> {
const auth = new ApolloLink((operation, forward) => {
userService.user$.subscribe((res) => {
setTokenInHeader(operation);
isRefreshToken = false;
});
return forward(operation);
});
const errorHandler = onError(
({ forward, graphQLErrors, networkError, operation }): any => {
if (graphQLErrors && !unHandledError) {
if (
graphQLErrors.some((x) =>
x.message.toLowerCase().includes('unauthorized')
)
) {
isRefreshToken = true;
return userService
.refreshToken()
.pipe(switchMap((res) => forward(operation)));
} else {
userService.logOut('Other Error');
}
unHandledError = true;
} else {
unHandledError = false;
}
}
);
const link = ApolloLink.from([errorHandler, auth, httpLink.create({ uri })]);
return {
link,
cache: new InMemoryCache(),
connectToDevTools: !environment.production,
};
}
function setTokenInHeader(operation) {
const tokenKey = isRefreshToken ? 'refreshToken' : 'token';
const token = localStorage.getItem(tokenKey) || '';
operation.setContext({
headers: {
token,
Accept: 'charset=utf-8',
},
});
}
@NgModule({
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, UserService],
},
],
})
export class GraphQLModule {}
用戶服務/身份驗證服務:
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { User, RefreshTokenGQL } from '../../../generated/graphql';
import jwt_decode from 'jwt-decode';
import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, tap } from 'rxjs/operators';
import { AlertService } from './alert.service';
@Injectable({
providedIn: 'root',
})
export class UserService {
private userSubject: BehaviorSubject<User>;
public user$: Observable<User>;
constructor(
private router: Router,
private injector: Injector,
private alert: AlertService
) {
const token = localStorage.getItem('token');
let user;
if (token && token !== 'undefined') {
try {
user = jwt_decode(token);
} catch (error) {
console.log('error', error);
}
}
this.userSubject = new BehaviorSubject<User>(user);
this.user$ = this.userSubject.asObservable();
}
setToken(token?: string, refreshToken?: string) {
let user;
if (token) {
user = jwt_decode(token);
localStorage.setItem('token', token);
localStorage.setItem('refreshToken', refreshToken);
} else {
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
}
this.userSubject.next(user);
return user;
}
logOut(msg?: string) {
if (msg) {
this.alert.addInfo('Logging out...', msg);
}
this.setToken();
this.router.navigateByUrl('/auth/login');
}
getUser() {
return this.userSubject.value;
}
refreshToken() {
const refreshTokenMutation = this.injector.get<RefreshTokenGQL>(
RefreshTokenGQL
);
return refreshTokenMutation.mutate().pipe(
tap(({ data: { refreshToken: res } }) => {
this.setToken(res.token, res.refreshToken);
}),
catchError((error) => {
console.log('On Refresh Error: ', error);
this.logOut('Session Expired, Log-in again');
return throwError('Session Expired, Log-in again');
})
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.