#How can i use an injection token in a factory function?

8 messages · Page 1 of 1 (latest)

violet sky
#

In my app.module

 providers: [UserService,
    { provide: BFF_URL, useValue: environment.bffUrl },
  ],

Then in my graphql.module (nx library):

export function createDefaultApollo(httpLink: HttpLink, @Inject(BFF_URL) baseUrl: string): ApolloClientOptions<any> {
    const cache = new InMemoryCache({});

    // create http
    const http = httpLink.create({
        uri: baseUrl + '/graphql',
    });

    return {
        connectToDevTools: false,
        assumeImmutableResults: true,
        cache,
        link: ApolloLink.from([basicContext, errorLink, http]),
        defaultOptions: {
          watchQuery: {
              fetchPolicy: 'cache-and-network',
              errorPolicy: 'all',
          },
          query: {
              fetchPolicy: 'cache-first',
              errorPolicy: 'all',
          },
          mutate: {
              errorPolicy: 'all'
          }
        },
    };
}

@NgModule({
    imports: [CommonModule, HttpClientModule, ApolloModule],
    providers: [
        {
            provide: APOLLO_OPTIONS,
            useFactory: createDefaultApollo,
            deps: [HttpLink, BFF_URL],
        },
    ],
})
export class GraphQLModule {
}

it doesnt like @Inject(BFF_URL) baseUrl: string. How can i solve this?

#

Solved it

#
export function createDefaultApollo(httpLink: HttpLink,  baseUrl: string, production:boolean): ApolloClientOptions<any> {
    const cache = new InMemoryCache({});

    // create http
    const http = httpLink.create({
        uri: baseUrl + '/graphql',
    });

    return {
        connectToDevTools: !production,
        assumeImmutableResults: true,
        cache,
        link: ApolloLink.from([basicContext, errorLink, http]),
        defaultOptions: {
          watchQuery: {
              fetchPolicy: 'cache-and-network',
              errorPolicy: 'all',
          },
          query: {
              fetchPolicy: 'cache-first',
              errorPolicy: 'all',
          },
          mutate: {
              errorPolicy: 'all'
          }
        },
    };
}

@NgModule({
    imports: [CommonModule, HttpClientModule, ApolloModule],
})
export class GraphQLModule {
  static forRoot(bffUrl: string, isProduction:boolean): ModuleWithProviders<GraphQLModule> {
    return {
      ngModule: GraphQLModule,
      providers: [
        {
          provide: APOLLO_OPTIONS,
          useFactory: (http: HttpLink) => createDefaultApollo(http,bffUrl,isProduction),
          deps: [HttpLink]
        }
      ]
    }
  }
}

violet shuttle
#

Simply remove the @Inject(BFF_URL) .

violet sky
#

Hmm that might be even beter

#

Im gonna try

violet sky
#

that works

#

although i had to create a seperate module to make sure i didnt have a circular dependency