#Additional providers while using ConfigurableModuleBuilder

3 messages · Page 1 of 1 (latest)

silk shuttle
#

Hello. That is probably a silly question.
For me, register and async counterpart using useFactory seems trivial, but I'm not sure how to create providers when useExisting/useClass provided.

private static createStripeAsyncProvider(
    options: typeof STRIPE_ASYNC_OPTIONS_TYPE,
  ): Provider | Promise<Provider> {
    if (options.useFactory) {
      const config = options.useFactory();
      if (config instanceof Promise) {
        return config.then((resolvedConfig) => {
          return this.createStripeProvider(resolvedConfig);
        });
      } else {
        return this.createStripeProvider(config);
      }
    }

    if (options.useClass) {
      // ?
    }

    if (options.useExisting) {
      // ?
    }

    throw new Error('Invalid Stripe async options');
  }
#

And I am also not sure if I even use it right:

static registerAsync(
    options: typeof STRIPE_ASYNC_OPTIONS_TYPE,
  ): DynamicModule {
    const module = super.registerAsync(options);
    const stripeAsyncProvider = StripeModule.createStripeAsyncProvider(options);

    if (stripeAsyncProvider instanceof Promise) {
      stripeAsyncProvider.then((resolvedStripeAsyncProvider) => {
        if (module.providers) {
          module.providers.push(resolvedStripeAsyncProvider);
        } else {
          module.providers = [resolvedStripeAsyncProvider];
        }
      });
    } else {
      if (module.providers) {
        module.providers.push(stripeAsyncProvider);
      } else {
        module.providers = [stripeAsyncProvider];
      }
    }

    return module;
  }
silk shuttle
#

I realized how to do this by reading the documentation again. I don't have to create options myself, just use provided options token to inject when I create actual provider:

private static createStripeAsyncProvider(): Provider {
    return {
      provide: Stripe,
      useFactory: async (stripeOptions: typeof STRIPE_OPTIONS_TYPE) => {
        return this.createStripeProvider(stripeOptions);
      },
      inject: [STRIPE_MODULE_OPTIONS_TOKEN],
    };
  }