Comments (5)
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.
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.
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.
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.
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.
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)
- RabbitMQ Bug Microservices HOT 1
- nx 18 + nest + webpack + serverless breaking with error src/main.handler is undefined or not exported HOT 1
- NestJS doesn't handle "Operation failed: QueueDeclare" error from amqplib HOT 1
- Problems Encountered with NestJS and pnpm in a Monorepo Setup HOT 1
- grpc microservice stops listening to requests after version 10.3.3 (needs peer dependency) HOT 1
- perf: caching return value for some functions HOT 1
- The request body does not return an object whose value is an array of objects
- Jest spy doesn't work on Microservices Controller (EventPattern) E2E Tests
- Feature Request: Support for Bun.js HOT 2
- Multi-tenant app fail on first non durable tree request HOT 2
- Kafka Microservice Error When Consumer Has Not Joined the Consumer Group
- LoggerService transforms the instance of Error when controller throws an Error HOT 3
- Easy way to compose ORed validators HOT 1
- Not sure if it is bug or feature request, nest middleware in jest runs before any other express middleware HOT 2
- Devtools with microservices: Error: listen EADDRINUSE: address already in use :::8000 HOT 4
- Hooks in global module which imported more than twice might called multiple times HOT 2
- Nest crash when RouteConstraints is used without app versioning enabled HOT 3
- NestJS Mongoose populate() Not Working for Arrays of ObjectIds, But Works for Single ObjectId HOT 4
- Problem with File upload in Swagger HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from nest.