nestjs-dependency-injection
БесплатноБез исполняемых скриптовНе проверенUse when nestJS dependency injection with providers, modules, and decorators. Use when building modular NestJS applications.
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
NestJS Dependency Injection
Master NestJS dependency injection for building modular, testable Node.js applications with proper service architecture, provider patterns, and module organization.
Table of Contents
- Provider Patterns
- Module System
- Injection Scopes
- Advanced Patterns
- Best Practices
- Common Pitfalls
- Resources
Provider Patterns
Class Providers (Standard Pattern)
import { Injectable } from '@nestjs/common';
@Injectable()
export class UserService {
private users: User[] = [];
findAll(): User[] {
return this.users;
}
findById(id: string): User | undefined {
return this.users.find(user => user.id === id);
}
create(user: User): User {
this.users.push(user);
return user;
}
}
// Module registration
@Module({
providers: [UserService],
exports: [UserService],
})
export class UserModule {}
Value Providers
import { Module } from '@nestjs/common';
// Simple value provider
const DATABASE_CONNECTION = {
provide: 'DATABASE_CONNECTION',
useValue: {
host: 'localhost',
port: 5432,
database: 'mydb',
},
};
// Configuration value provider
const APP_CONFIG = {
provide: 'APP_CONFIG',
useValue: {
apiUrl: process.env.API_URL,
timeout: 5000,
retries: 3,
},
};
@Module({
providers: [DATABASE_CONNECTION, APP_CONFIG],
exports: [DATABASE_CONNECTION, APP_CONFIG],
})
export class ConfigModule {}
// Usage in service
@Injectable()
export class ApiService {
constructor(
@Inject('APP_CONFIG') private config: AppConfig,
) {}
async fetchData(): Promise<any> {
const response = await fetch(this.config.apiUrl, {
timeout: this.config.timeout,
});
return response.json();
}
}
Factory Providers
import { Injectable, Module } from '@nestjs/common';
// Simple factory provider
const CONNECTION_FACTORY = {
provide: 'DATABASE_CONNECTION',
useFactory: () => {
return createConnection({
type: 'postgres',
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT),
database: process.env.DB_NAME,
});
},
};
// Factory with dependencies
const CACHE_MANAGER = {
provide: 'CACHE_MANAGER',
useFactory: (config: ConfigService) => {
return createCacheManager({
store: config.get('CACHE_STORE'),
ttl: config.get('CACHE_TTL'),
max: config.get('CACHE_MAX_ITEMS'),
});
},
inject: [ConfigService],
};
@Module({
providers: [
ConfigService,
CONNECTION_FACTORY,
CACHE_MANAGER,
],
exports: ['DATABASE_CONNECTION', 'CACHE_MANAGER'],
})
export class DatabaseModule {}
Async Providers with useFactory
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
const DATABASE_PROVIDER = {
provide: 'DATABASE_CONNECTION',
useFactory: async (config: ConfigService) => {
const connection = await createConnection({
type: 'postgres',
host: config.get('DB_HOST'),
port: config.get('DB_PORT'),
username: config.get('DB_USER'),
password: config.get('DB_PASSWORD'),
database: config.get('DB_NAME'),
});
await connection.runMigrations();
return connection;
},
inject: [ConfigService],
};
const REDIS_PROVIDER = {
provide: 'REDIS_CLIENT',
useFactory: async (config: ConfigService) => {
const client = createClient({
url: config.get('REDIS_URL'),
});
await client.connect();
client.on('error', (err) => {
console.error('Redis error:', err);
});
return client;
},
inject: [ConfigService],
};
@Module({
providers: [DATABASE_PROVIDER, REDIS_PROVIDER],
exports: ['DATABASE_CONNECTION', 'REDIS_CLIENT'],
})
export class DataModule {}
Token-Based Injection with String Tokens
import { Inject, Injectable, Module } from '@nestjs/common';
// Define string tokens as constants
export const LOGGER_TOKEN = 'LOGGER';
export const METRICS_TOKEN = 'METRICS';
export const API_CLIENT_TOKEN = 'API_CLIENT';
// Provider definitions
const LOGGER_PROVIDER = {
provide: LOGGER_TOKEN,
useFactory: () => {
return createLogger({
level: process.env.LOG_LEVEL || 'info',
format: 'json',
});
},
};
const METRICS_PROVIDER = {
provide: METRICS_TOKEN,
useValue: createMetricsClient(),
};
@Module({
providers: [LOGGER_PROVIDER, METRICS_PROVIDER],
exports: [LOGGER_TOKEN, METRICS_TOKEN],
})
export class ObservabilityModule {}
// Usage in service
@Injectable()
export class UserService {
constructor(
@Inject(LOGGER_TOKEN) private logger: Logger,
@Inject(METRICS_TOKEN) private metrics: MetricsClient,
) {}
async createUser(data: CreateUserDto): Promise<User> {
this.logger.info('Creating user', { email: data.email });
this.metrics.increment('user.created');
const user = awai
Установить nestjs-dependency-injection в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
BashReadWriteEditGlobGrepFAQ
Что делает скилл nestjs-dependency-injection?
Use when nestJS dependency injection with providers, modules, and decorators. Use when building modular NestJS applications.
Как установить скилл nestjs-dependency-injection?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл nestjs-dependency-injection запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic