Application - Client - Angular & GraphQL
Để giao tiếp với server sử dụng Apollo Server, client có thể sử dụng Apollo Client. Với angular có thể sử dụng Apollo Angular.
Install:
Install theo hướng dẫn sau https://apollo-angular.com/docs/get-started
GraqhQL Module:
...
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { ApolloLink } from 'apollo-link';
const UNAUTHENTICATED_CODE = 'UNAUTHENTICATED';
@NgModule({
exports: [
ApolloModule,
HttpLinkModule,
],
})
export class GraphQLModule {
constructor(
apollo: Apollo,
httpLink: HttpLink,
public authService: AuthenticationService,
public notificationService: NotificationService,
) {
const http = httpLink.create({uri: `${environment.apiUrl}/graphql`});
const authLink = new ApolloLink((operation, forward) => {
if (this.isExceptedOperator(operation.operationName)) {
operation.setContext(({headers}) => ({
headers: {
token: this.authService.getToken(),
...headers
}
}));
}
return forward(operation);
});
const subscriptionClient = new SubscriptionClient(
`${environment.webSocketUrl}/graphql`,
{
reconnect: true,
connectionParams: {
authToken: this.authService.getToken(),
},
},
);
const wsLink = new WebSocketLink(subscriptionClient);
const errorLink = onError(({graphQLErrors, networkError, operation, forward}) => {
if (graphQLErrors) {
for (const err of graphQLErrors) {
const code = err.extensions.code;
if (code && code === UNAUTHENTICATED_CODE && this.isExceptedOperator(operation.operationName)) {
const oldHeaders = operation.getContext().headers;
// Retry the request
return promiseToObservable(this.getRefreshToken())
.flatMap(
(res: any) => {
const data: RefreshTokenMutation = res.data;
if (data.refreshToken && data.refreshToken.token) {
const accessToken = res.data.refreshToken.token;
this.authService.setToken(accessToken);
operation.setContext({
headers: {
...oldHeaders,
token: accessToken
},
});
return forward(operation)
} else {
this.authService.logout();
window.location.reload();
}
}
);
} else {
this.notificationService.openSnackBar(err.message);
}
}
}
if (networkError) {
console.log('networkError', networkError);
}
});
const httpLinkWithErrorHandling = ApolloLink.from([
errorLink,
authLink.concat(http),
]);
// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
// split based on operation type
({query}) => {
const {kind, operation} = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLinkWithErrorHandling,
);
apollo.create({
// By default, this client will send queries to the
// `/graphql` endpoint on the same host
link,
cache: new InMemoryCache({
addTypename: false
})
});
}
getRefreshToken(): Promise<any> {
return this.authService
.refreshToken()
.pipe(first())
.toPromise();
}
isExceptedOperator(operationName: string) {
return !['loginMutation', 'refreshTokenMutation'].includes(operationName)
}
}
Http Link: Gửi GraphQL operation đến server. Trường hợp muốn set token vào headers trước khi gửi request thì thêm authLink.
authLink.concat(http),
errorLink: Handle trong trường hợp access token hết hạn, sau khi request 1 token mới sẽ retry lại request ban đầu. Để có thể retry được request cần
return forward(operation)
tại functiononError()
. NhưnggetRefreshToken
đang trả về Observable nên mình có dùng thêm functionpromiseToObservable
export default promise => new Observable((subscriber: any) => { promise.then( (value) => { if (subscriber.closed) return; subscriber.next(value); subscriber.complete(); }, err => subscriber.error(err) ); return subscriber; });
Version rxjs hiện đang là 6.6.7, khuyến nghi nên dùng lastvaluefrom đối với rxjs ^7
wsLink: Thực thi subscription qua WebSocket. Thêm authToken trong connectionParams để verify client.
Series:
- Preview
- Server - NestJs & GraphQL
- Server - Module
- Server - Validation
- Server - Authentication
- Server - Supscription & Upload file
- Client - Angular & GraphQL
GitHub: https://github.com/ninhnguyen22/nestjs-angular-graphql