Skip to content

Instantly share code, notes, and snippets.

@paztek
Last active July 17, 2020 23:28
Show Gist options
  • Save paztek/9ecced3e00d76b93e326abc91bd585da to your computer and use it in GitHub Desktop.
Save paztek/9ecced3e00d76b93e326abc91bd585da to your computer and use it in GitHub Desktop.
nestjs-ioc-example-2
import { Module, OnModuleInit } from '@nestjs/common';
import { DrinkService } from './drink.service';
import { DiscoveryModule, DiscoveryService } from "@nestjs/core";
import { DRINK_PROVIDER, DrinkProvider } from "./drink.provider";
@Module({
imports: [
DiscoveryModule,
],
providers: [
DrinkService,
],
})
export class DrinkModule implements OnModuleInit {
constructor(
private readonly discovery: DiscoveryService,
private readonly drinkService: DrinkService,
) {}
onModuleInit(): any {
const wrappers = this.discovery.getProviders();
const drinkProviders = wrappers
.filter((wrapper) => wrapper.metatype && Reflect.getMetadata(DRINK_PROVIDER, wrapper.metatype))
.map((wrapper) => wrapper.instance) as DrinkProvider[];
drinkProviders.forEach((provider) => this.drinkService.registerProvider(provider));
}
}
import { SetMetadata } from '@nestjs/common';
import { Drink } from './drink.model';
export const DRINK_PROVIDER = 'DrinkProvider';
export interface DrinkProvider {
getDrinks(): Promise<Drink[]>;
}
export const DrinkProviderDecorator = () => SetMetadata(DRINK_PROVIDER, true);
import { Injectable } from '@nestjs/common';
import { DrinkProvider, DrinkProviderDecorator } from '../drink.provider';
import { Drink } from '../drink.model';
@Injectable()
@DrinkProviderDecorator()
export class SpiritDrinkProvider implements DrinkProvider {
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 { SpiritDrinkProvider } from './spirit.drink.provider';
@Module({
providers: [
SpiritDrinkProvider,
],
})
export class SpiritModule {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment