@darkhorseone/primeforge-common
v1.0.1
Published
Shared services and utilities for NestJS applications in PrimeForge
Readme
@darkhorseone/primeforge-common
Shared services and utilities for NestJS applications in PrimeForge
A comprehensive collection of reusable NestJS modules, services, and utilities designed to accelerate development and maintain consistency across microservices.
📦 Installation
Publish the compiled package to your private registry (for example GitHub Packages or a self-hosted Verdaccio) and consume it like any other dependency. The prepublishOnly script builds dist/ automatically before the publish step.
# Configure your .npmrc once per environment
npm config set //npm.pkg.github.com/:_authToken=<YOUR_TOKEN>
npm config set @darkhorseone:registry=https://npm.pkg.github.com
# Publish from this repository
npm publish --registry=https://npm.pkg.github.comOnce the package is available in the registry:
npm install @darkhorseone/primeforge-commonAdjust the scope/registry values to match your setup. For local development without publishing,
npm install @darkhorseone/primeforge-common@file:../primeforge-commonremains supported.
🚀 Quick Start
import { Module } from "@nestjs/common";
import { ConfigModule, LoggerModule, HealthModule } from "@darkhorseone/primeforge-common";
@Module({
imports: [ConfigModule, LoggerModule.forRoot(), HealthModule.forRoot()],
})
export class AppModule {}📋 Table of Contents
🧩 Modules
ConfigModule
Centralized configuration management with environment validation and type safety.
Features:
- Environment variable validation
- Type-safe configuration access
- Support for multiple environments
- Auto-loading of .env files
Usage:
import { ConfigModule, ConfigService } from "@darkhorseone/primeforge-common";
@Module({
imports: [ConfigModule],
})
export class AppModule {}
// In your service
@Injectable()
export class MyService {
constructor(private configService: ConfigService) {}
getAppConfig() {
return this.configService.app; // Type-safe access
}
}Available Configurations:
app- Application settings (port, host, environment)database- Database connection settingsredis- Redis configurationjwt- JWT token configurationemail- Email service settingslogger- Logging configurationsecurity- Security settingsmonitoring- Health check and metrics settings
LoggerModule
Structured logging service with multiple output formats and log levels.
Features:
- JSON and pretty-print formats
- Multiple log levels (debug, info, warn, error)
- Context-aware logging
- File and console output
- Request correlation IDs
Usage:
import { LoggerModule, LoggerService } from "@darkhorseone/primeforge-common";
@Module({
imports: [
LoggerModule.forRoot({
level: "info",
format: "json",
outputToFile: true,
}),
],
})
export class AppModule {}
// In your service
@Injectable()
export class MyService {
constructor(private logger: LoggerService) {}
doSomething() {
this.logger.info("Operation started", { userId: "123" });
this.logger.warn("Warning message");
this.logger.error("Error occurred", { error: "details" });
}
}HealthModule
Comprehensive health checking and monitoring for your applications.
Features:
- Basic and detailed health checks
- Readiness and liveness probes
- Prometheus-style metrics
- Database connectivity checks
- System resource monitoring
Usage:
import { HealthModule } from "@darkhorseone/primeforge-common";
@Module({
imports: [
HealthModule.forRoot({
enableDetailedHealth: true,
database: {
enabled: true,
timeout: 3000,
},
}),
],
})
export class AppModule {}Available Endpoints:
GET /health- Basic health checkGET /health/detailed- Detailed system informationGET /health/ready- Readiness probeGET /health/live- Liveness probeGET /metrics- Prometheus metrics
EmailModule
Core email sending service focused on delivery through SendGrid.
Note: EmailModule now provides only core email delivery functionality. For business logic like welcome emails and templates, implement dedicated services in your application modules.
Features:
- SendGrid integration
- Direct email sending
- Batch email support
- Scheduled email delivery
- Attachment support
- Email status tracking
Usage:
import { EmailModule, EmailService } from "@darkhorseone/primeforge-common";
@Module({
imports: [
EmailModule.forRootAsync({
useFactory: (configService: ConfigService) => configService.email,
inject: [ConfigService],
}),
],
})
export class AppModule {}
// In your service
@Injectable()
export class MyService {
constructor(private emailService: EmailService) {}
async sendNotification(user: User) {
await this.emailService.sendEmail({
to: { email: user.email, name: user.name },
subject: "Notification",
htmlContent: "<h1>Hello!</h1><p>This is a notification.</p>",
textContent: "Hello! This is a notification.",
});
}
}For Template Management:
Create an EmailTemplateService in your application to handle business logic:
// See EMAIL_MIGRATION_GUIDE.md for complete examples
@Injectable()
export class EmailTemplateService {
constructor(
private prisma: PrismaService,
private emailService: EmailService
) {}
async sendWelcomeEmail(email: string, name: string) {
const template = await this.getTemplate("welcome");
const content = this.processTemplate(template.html_body, { name });
return this.emailService.sendEmail({
to: { email },
subject: template.subject,
htmlContent: content,
});
}
}AuthModule
JWT-based authentication and authorization utilities.
Features:
- JWT token verification
- Authentication guards
- Role-based access control
- Permission checking
- Token management
Usage:
import { AuthModule, JwtAuthGuard } from "@darkhorseone/primeforge-common";
@Module({
imports: [
AuthModule.forRootAsync({
useFactory: (configService: ConfigService) => configService.jwt,
inject: [ConfigService],
}),
],
})
export class AppModule {}
// In your controller
@Controller("users")
@UseGuards(JwtAuthGuard)
export class UsersController {
@Get("profile")
@Roles("user", "admin")
getProfile(@CurrentUser() user: any) {
return user;
}
}🛠 Common Utilities
Decorators
@Public() - Mark routes as public (no authentication required)
@Get('public-endpoint')
@Public()
getPublicData() {
return { message: 'This is public' };
}@Roles(...) - Require specific roles
@Get('admin-only')
@Roles('admin')
getAdminData() {
return { message: 'Admin only' };
}@RequirePermissions(...) - Require specific permissions
@Get('protected')
@RequirePermissions('read:users')
getProtectedData() {
return { message: 'Protected data' };
}@CurrentUser() - Inject current user from JWT
@Get('profile')
getProfile(@CurrentUser() user: JwtPayload) {
return user;
}DTOs
PaginationDto - Standard pagination parameters
export class GetUsersDto extends PaginationDto {
@IsOptional()
@IsString()
search?: string;
}Filters
HttpExceptionFilter - Global exception handling
app.useGlobalFilters(new HttpExceptionFilter(logger));Utilities
HashUtil - Password hashing and token generation
import { HashUtil } from "@darkhorseone/primeforge-common";
// Hash password
const hashedPassword = await HashUtil.hashPassword("plaintext");
// Verify password
const isValid = await HashUtil.verifyPassword(hash, "plaintext");
// Generate token
const token = HashUtil.generateToken(32);
// Generate OTP
const otp = HashUtil.generateOTP(6);ValidationUtil - Common validation functions
import { ValidationUtil } from "@darkhorseone/primeforge-common";
// Validate email
const isValidEmail = ValidationUtil.isValidEmail("[email protected]");
// Validate password strength
const { isValid, errors, score } =
ValidationUtil.validatePasswordStrength("MyPassword123!");
// Validate UUID
const isValidUUID = ValidationUtil.isValidUUID(
"123e4567-e89b-12d3-a456-426614174000"
);💡 Examples
Complete Application Setup
import { Module } from "@nestjs/common";
import {
ConfigModule,
ConfigService,
LoggerModule,
HealthModule,
EmailModule,
AuthModule,
HttpExceptionFilter,
} from "@darkhorseone/primeforge-common";
@Module({
imports: [
// Global configuration
ConfigModule,
// Structured logging
LoggerModule.forRootAsync({
useFactory: (configService: ConfigService) => configService.logger,
inject: [ConfigService],
}),
// Health monitoring
HealthModule.forRoot({
enableDetailedHealth: true,
database: { enabled: true, timeout: 3000 },
}),
// Email service
EmailModule.forRootAsync({
useFactory: (configService: ConfigService) => configService.email,
inject: [ConfigService],
}),
// JWT Authentication
AuthModule.forRootAsync({
useFactory: (configService: ConfigService) => configService.jwt,
inject: [ConfigService],
}),
],
})
export class AppModule {}Secure Controller with Authentication
import { Controller, Get, Post, Body, UseGuards } from "@nestjs/common";
import {
JwtAuthGuard,
Roles,
RequirePermissions,
CurrentUser,
Public,
PaginationDto,
JwtPayload,
} from "@darkhorseone/primeforge-common";
@Controller("api/users")
@UseGuards(JwtAuthGuard)
export class UsersController {
@Get("public")
@Public()
getPublicInfo() {
return { message: "This endpoint is public" };
}
@Get("profile")
getProfile(@CurrentUser() user: JwtPayload) {
return { user };
}
@Get("admin")
@Roles("admin")
getAdminData() {
return { message: "Admin only data" };
}
@Get("users")
@RequirePermissions("read:users")
getUsers(@Query() pagination: PaginationDto) {
return { users: [], meta: pagination };
}
}⚙️ Configuration
Environment Variables
# Application
APP_NAME=MyApp
PORT=3000
HOST=0.0.0.0
NODE_ENV=development
GLOBAL_PREFIX=api
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/db
# JWT
JWT_SECRET=your-secret-key
JWT_EXPIRES_IN=15m
JWT_REFRESH_SECRET=your-refresh-secret
JWT_REFRESH_EXPIRES_IN=7d
# Email (SendGrid)
SENDGRID_API_KEY=your-sendgrid-api-key
[email protected]
# Redis (optional)
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
# Security
CORS_ORIGINS=http://localhost:3000,http://localhost:3001TypeScript Configuration
Ensure your tsconfig.json includes:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}📚 Migration Guide
If you're upgrading from a previous version that included template management features in EmailService, please refer to our comprehensive migration guide:
📖 Email Service Migration Guide
The guide covers:
- ✅ Step-by-step migration instructions
- ✅ Interface changes and new features
- ✅ Code examples for common patterns
- ✅ Testing updates
- ✅ Troubleshooting tips
🔗 API Reference
Types and Interfaces
All modules export comprehensive TypeScript types:
import type {
AppConfig,
DatabaseConfig,
JwtConfig,
EmailConfig,
LoggerConfig,
HealthConfig,
JwtPayload,
EmailMessage,
PaginatedResult,
} from "@darkhorseone/primeforge-common";Constants
import {
AUTH_IS_PUBLIC_KEY,
AUTH_ROLES_KEY,
AUTH_PERMISSIONS_KEY,
} from "@darkhorseone/primeforge-common";🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📝 License
This project is licensed under the UNLICENSED License - see the package.json file for details.
🔍 Troubleshooting
Common Issues
Module not found errors:
npm install reflect-metadataDecorator errors:
Enable experimental decorators in your tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}Environment variables not loading:
Ensure you have the correct .env file structure and that ConfigModule is imported first.
For more detailed examples and advanced usage, please refer to the individual module documentation in the /docs directory.
