import { ModuleWithProviders, NgModule } from '@angular/core'; import { APOLLO_OPTIONS, ApolloModule } from 'apollo-angular'; import { HttpLink } from 'apollo-angular/http'; import { InMemoryCache } from '@apollo/client/core'; import { HttpClientModule, provideHttpClient, withInterceptors } from '@angular/common/http'; import { setContext } from '@apollo/client/link/context'; import { AuthService } from './auth/auth.service'; import { AuthInterceptor } from './auth/auth-interceptor'; import { IDomainKeys } from './interfaces/domain-key.interface'; import { AUTH_CONFIG, IAuthConfig } from './interfaces/auth-config.interface'; @NgModule({ exports: [ApolloModule, HttpClientModule], declarations: [], providers: [ provideHttpClient( withInterceptors([AuthInterceptor]) ), AuthService ], }) export class GraphQLModule { static forRoot(environment: any): ModuleWithProviders { const currentSubdomain = window.location.hostname.includes('.') ? window.location.hostname.split('.')[0] : window.location.hostname; const findSubdomine = environment.domainKeys.find( (apiKey: IDomainKeys) => apiKey.domain === currentSubdomain ); const authLink = setContext(() => { const headers: any = {}; if (findSubdomine) { headers['api-key'] = findSubdomine.key; } return { headers }; }); return { ngModule: GraphQLModule, providers: [ { provide: AUTH_CONFIG, useValue: { refresh_url: environment.refresh_url, refresh_token_key: environment.refresh_token_key ?? 'access_token' } as IAuthConfig }, { provide: APOLLO_OPTIONS, useFactory(httpLink: HttpLink, authService: AuthService) { return { cache: new InMemoryCache(), link: authLink.concat( httpLink.create({ uri: () => authService.getToken() ? environment.base_url_private : environment.base_url_public, }) ), }; }, deps: [HttpLink, AuthService], } ] }; } }