Skip to content

Instantly share code, notes, and snippets.

@sezanzeb
Last active March 13, 2023 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sezanzeb/4cca6f0e7689d75b5a1ec546c471c430 to your computer and use it in GitHub Desktop.
Save sezanzeb/4cca6f0e7689d75b5a1ec546c471c430 to your computer and use it in GitHub Desktop.
Example on how to get providers into dynamic objects
import { INestApplication, Injectable, Logger, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
/**
* A kind of hero that casts spells.
*/
class Wizard {
constructor(
private readonly name: string,
private readonly level: number,
private readonly environmentService: EnvironmentService
) { }
public castFire(): void {
if (this.environmentService.isRainy()) {
throw new Error('Cannot cast fire if it rains');
}
// cast fire
// ...
}
}
/**
* To query information about the environment a hero is currently in.
*/
@Injectable()
class EnvironmentService {
public isRainy(): boolean {
return true;
}
}
/**
* Factory to create heroes of various kinds. Allows injecting other services into
* heroes.
*/
@Injectable()
class HeroFactory {
constructor(private readonly environmentService: EnvironmentService) { }
public createWizard(name: string): Wizard {
return new Wizard(name, 1, this.environmentService);
}
}
@Module({
providers: [
HeroFactory,
EnvironmentService
]
})
export class GameModule { }
/**
* Run the example
*/
const runGame = async (): Promise<void> => {
const app: INestApplication = await NestFactory.create(GameModule);
const heroFactory = app.get<HeroFactory>(HeroFactory);
const wizard = heroFactory.createWizard('Robin');
wizard.castFire();
};
runGame().catch((error: Error): void => {
Logger.error(error);
});
/*
Output:
ts-node-esm wizard.ts
[Nest] 19273 - 03/13/2023, 11:51:32 AM LOG [NestFactory] Starting Nest application...
[Nest] 19273 - 03/13/2023, 11:51:32 AM LOG [InstanceLoader] GameModule dependencies initialized +19ms
[Nest] 19273 - 03/13/2023, 11:51:32 AM ERROR Error: Cannot cast fire if it rains
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment