'NestJS load class dynamically
I have a couple of parser services which I want to load based on condition.
The condition is a version so if the version is 1, Service1 will be loaded if version is 2, Service2 will be loaded, it continues in this pattern.
const version = 1;
// load service class based on version Service1 in this case
I could use switch case statement to load the exact service class based on the version but there could be a lot of service classes and it would not be neat.
Is there any way I could do this in nestJs?
Solution 1:[1]
You can use class provider or factory provider
const serviceProvider = {
provide: Service,
useClass:
version === 1
? Service1
: Service2,
};
@Module({
providers: [serviceProvider],
})
export class MyModule {}
Solution 2:[2]
Javascript dynamic import
something like this
function serviceFactory(){
return import(`service-${version}`)
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AZ_ |
| Solution 2 | mehari |
