GithubHelp home page GithubHelp logo

Comments (5)

KostyaTretyak avatar KostyaTretyak commented on May 7, 2024 1

First of all, I agree with you that it's confusing, but it looks like I can understand why it happens.
Try running the following code:

import { NestFactory } from '@nestjs/core';
import { Inject, Module } from '@nestjs/common';

const tokenSymbol = Symbol('Some-Token');

@Module({
  providers: [{ provide: tokenSymbol, useValue: 'Batman' }],
  exports: [tokenSymbol],
})
class FirstModule {}

@Module({
  imports: [FirstModule],
  providers: [{ provide: tokenSymbol, useValue: 'Robin' }],
})
class SecondModule {
  constructor(@Inject(tokenSymbol) public batmanOrRobin: string) {}
}

async function bootstrap() {
  const app = await NestFactory.create(SecondModule);
  const value1 = app.get(tokenSymbol);
  console.log('per application:', value1);
  const value2 = app.get(SecondModule);
  console.log('per module:', value2.batmanOrRobin);
}
bootstrap();

This code prints the following values to the console:

per application: Batman
per module: Robin

The app.get(tokenSymbol) method returns the application-level provider value. First, Nest at the application level adds a provider with tokenSymbol taking the value from the SecondModule (Robin), and then this value is replaced by the value that is written in the FirstModule (Batman).

So the value returned by the Nest DI container depends on the scope.

from nest.

chandu avatar chandu commented on May 7, 2024 1

Finally was able to make the tests pass (used select method of the NestApplication to set a module context).
I assumed the NestFactory.create would simulate something similar to select method for the root module passed as arg automatically, but apparently not.

image

  describe('Can override a provider imported via a module', () => {
    it('should work', async () => {
      @Module({
        providers: [{ provide: tokenSymbol, useValue: 'Batman' }],
      })
      class FirstModule {}

      @Module({
        imports: [FirstModule],
        providers: [
          {
            provide: tokenSymbol,
            useFactory() {
              return 'Robin';
            },
          },
        ],
        exports: [tokenSymbol],
      })
      class SecondModule {}

      let app: INestApplication | null = null;
      try {
        app = await NestFactory.create(SecondModule, {
          logger: false,
        });

        const selectedApp = app.select(SecondModule);

        const value = selectedApp.get(tokenSymbol, {
          strict: true,
        });
        expect(value).toEqual('Robin');
      } finally {
        app?.close();
      }
    });
  });

from nest.

KostyaTretyak avatar KostyaTretyak commented on May 7, 2024

By the way, you don't even export any providers from FirstModule. It seems that the problem is only observed in your tests. In the real application, everything works as you would expect:

import { NestFactory } from '@nestjs/core';
import { Controller, Get, Inject, Module } from '@nestjs/common';

const tokenSymbol = Symbol('Some-Token');

@Module({
  providers: [{ provide: tokenSymbol, useValue: 'Batman' }],
  exports: [tokenSymbol],
})
class FirstModule {}

@Controller()
export class FirstController {
  constructor(@Inject(tokenSymbol) private batmanOrRobin: string) {}

  @Get()
  getHello(): string {
    return this.batmanOrRobin;
  }
}

@Module({
  imports: [FirstModule],
  providers: [{ provide: tokenSymbol, useValue: 'Robin' }],
  controllers: [FirstController],
})
class SecondModule {}

@Module({
  imports: [SecondModule],
})
export class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

from nest.

chandu avatar chandu commented on May 7, 2024

By the way, you don't even export any providers from FirstModule. It seems that the problem is only observed in your tests. In the real application, everything works as you would expect:

import { NestFactory } from '@nestjs/core';
import { Controller, Get, Inject, Module } from '@nestjs/common';

const tokenSymbol = Symbol('Some-Token');

@Module({
  providers: [{ provide: tokenSymbol, useValue: 'Batman' }],
  exports: [tokenSymbol],
})
class FirstModule {}

@Controller()
export class FirstController {
  constructor(@Inject(tokenSymbol) private batmanOrRobin: string) {}

  @Get()
  getHello(): string {
    return this.batmanOrRobin;
  }
}

@Module({
  imports: [FirstModule],
  providers: [{ provide: tokenSymbol, useValue: 'Robin' }],
  controllers: [FirstController],
})
class SecondModule {}

@Module({
  imports: [SecondModule],
})
export class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

I have updated my test to use NestFactory.create and it's still failing.
I have pushed the changes I have done to : https://github.com/chandu/nest-override-modules
Speciafically, https://github.com/chandu/nest-override-modules/blob/main/src/override.spec.ts#L38

from nest.

chandu avatar chandu commented on May 7, 2024

Thanks @KostyaTretyak . Yes, I have run a similar check and am able to verify the returned values.
I think the root cause of my confusion is aroud how the NestApplication instance behaves w.r.t to the root module.
What still surprises me is the app is able to resolve a provider from FirstModule even when it is not exported and the FirstModule is not used as a root module.

from nest.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.