Skip to content

Instantly share code, notes, and snippets.

@paztek
Last active July 17, 2020 22:21
Show Gist options
  • Save paztek/c4858998deedb93fd496cd1302314e78 to your computer and use it in GitHub Desktop.
Save paztek/c4858998deedb93fd496cd1302314e78 to your computer and use it in GitHub Desktop.
nestjs-ioc-example-1
export interface Drink {
name: string;
alcoholByVolume: number;
}
import { Module } from '@nestjs/common';
import { DrinkService } from './drink.service';
@Module({
providers: [
DrinkService,
],
exports: [
DrinkService,
],
})
export class DrinkModule {}
import { Drink } from './drink.model';
export interface DrinkProvider {
getDrinks(): Promise<Drink[]>;
}
import { Injectable } from '@nestjs/common';
import { Drink } from './drink.model';
import { DrinkProvider } from './drink.provider';
@Injectable()
export class DrinkService {
private readonly providers: DrinkProvider[] = [];
registerProvider(provider: DrinkProvider): void {
this.providers.push(provider);
}
async getDrinks(): Promise<Drink[]> {
const drinks: Drink[] = [];
for (const provider of this.providers) {
drinks.push(...await provider.getDrinks());
}
return drinks;
}
}
import { Injectable } from '@nestjs/common';
import { DrinkProvider } from '../drink.provider';
import { Drink } from '../drink.model';
import { DrinkService } from '../drink.service';
@Injectable()
export class SpiritDrinkProvider implements DrinkProvider {
// This is the weird part that we'll improve
constructor(
drinkService: DrinkService,
) {
drinkService.registerProvider(this);
}
public getDrinks(): Promise<Drink[]> {
return Promise.resolve([
{
name: 'Rum',
alcoholByVolume: 45,
},
{
name: 'Arrack',
alcoholByVolume: 50,
},
{
name: 'Cognac',
alcoholByVolume: 40,
},
]);
}
}
import { Module } from '@nestjs/common';
import { DrinkModule } from '../drink.module';
import { SpiritDrinkProvider } from './spirit.drink.provider';
@Module({
imports: [
DrinkModule,
],
providers: [
SpiritDrinkProvider,
],
})
export class SpiritModule {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment