Skip to content

Commit

Permalink
GraphQL: added Authorization Bearer header
Browse files Browse the repository at this point in the history
  • Loading branch information
zaychenko-sergei committed Aug 29, 2023
1 parent 1a383e3 commit 9b2dfe6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 33 deletions.
23 changes: 17 additions & 6 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ import { MatToolbarModule } from "@angular/material/toolbar";
import { NgbModule, NgbTypeaheadModule } from "@ng-bootstrap/ng-bootstrap";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatIconModule } from "@angular/material/icon";
import { HttpClient, HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import { HttpClient, HttpClientModule, HTTP_INTERCEPTORS, HttpHeaders } from "@angular/common/http";
import { MatTableModule } from "@angular/material/table";
import { CdkTableModule } from "@angular/cdk/table";
import { InMemoryCache } from "@apollo/client/core";
import { ApolloLink, InMemoryCache, NextLink, Operation } from "@apollo/client/core";
import { SearchApi } from "./api/search.api";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { SearchService } from "./search/search.service";
Expand Down Expand Up @@ -66,6 +66,7 @@ import { LoggedUserService } from "./auth/logged-user.service";
import { firstValueFrom } from "rxjs";
import { LoginService } from "./auth/login/login.service";
import { logError } from "./common/app.helpers";
import AppValues from "./common/app.values";

const Services = [
{
Expand Down Expand Up @@ -93,6 +94,19 @@ const Services = [
{
provide: APOLLO_OPTIONS,
useFactory: (httpLink: HttpLink, appConfig: AppConfigService) => {
const httpMainLink: ApolloLink = httpLink.create({ uri: appConfig.apiServerGqlUrl });

const authorizationMiddleware: ApolloLink = new ApolloLink((operation: Operation, forward: NextLink) => {
const accessToken: string | null = localStorage.getItem(AppValues.LOCAL_STORAGE_ACCESS_TOKEN);
if (accessToken) {
operation.setContext({
headers: new HttpHeaders().set("Authorization", `Bearer ${accessToken}`),
});
}

return forward(operation);
});

return {
cache: new InMemoryCache({
typePolicies: {
Expand All @@ -102,9 +116,7 @@ const Services = [
},
},
}),
link: httpLink.create({
uri: appConfig.apiServerGqlUrl,
}),
link: authorizationMiddleware.concat(httpMainLink),
};
},
deps: [HttpLink, AppConfigService],
Expand Down Expand Up @@ -179,7 +191,6 @@ const MatModules = [
}),
NgbModule,
NgbTypeaheadModule,
//GraphQLModule,
HttpClientModule,
CdkTableModule,
...MatModules,
Expand Down
27 changes: 0 additions & 27 deletions src/app/graphql.module.ts

This file was deleted.

0 comments on commit 9b2dfe6

Please sign in to comment.