@hqxyz/hq-node-commons v1.3.0
HQ Node Commons
A collection of common utilities and libraries for NestJS TypeScript projects.
Installation
npm install --save @hq/node-commonsFeatures
- HTTP utilities (response formats, exceptions)
- Common validators
- Useful decorators
- Date and object utilities
- Configuration validation
- Slack notifications with error reporting
Usage
import {
ApiResponseBuilder,
DateUtils,
Log,
StringValidator,
ConfigValidator,
ConfigSchema,
NotificationsModule,
SlackService
} from '@hq/node-commons';
// Use ApiResponseBuilder
const response = ApiResponseBuilder.success({ id: 1, name: 'Example' });
// Use DateUtils
const today = new Date();
const tomorrow = DateUtils.addDays(today, 1);
// Use decorators
class UserService {
@Log({ logResult: true })
async findById(id: string) {
// Method implementation
}
}
// Use validators
const isValidEmail = StringValidator.isEmail('example@example.com');
// Use configuration validation
@Module({
imports: [
ConfigModule.forRoot({
validate: ConfigSchema.createValidator(
ConfigSchema.commonValidators(),
ConfigSchema.databaseValidators()
)
}),
NotificationsModule.register()
]
})
export class AppModule {}Documentation
HTTP Utilities
ApiResponse
Standardized API response format:
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: {
code: string;
message: string;
details?: any;
};
meta?: {
pagination?: {
page: number;
limit: number;
total: number;
totalPages: number;
};
[key: string]: any;
};
}ApiResponseBuilder
Helper to create standardized API responses:
ApiResponseBuilder.success(data, meta)- Create a success responseApiResponseBuilder.error(code, message, details)- Create an error responseApiResponseBuilder.paginated(data, page, limit, total, additionalMeta)- Create a paginated response
HTTP Exceptions
Custom HTTP exceptions with standardized format:
HttpException- Base exceptionBadRequestException- 400 Bad RequestUnauthorizedException- 401 UnauthorizedForbiddenException- 403 ForbiddenNotFoundException- 404 Not Found
Validators
StringValidator
String validation utilities:
StringValidator.isEmail(value)- Check if string is a valid emailStringValidator.isUrl(value)- Check if string is a valid URLStringValidator.isUuidV4(value)- Check if string is a valid UUID v4StringValidator.isAlphanumeric(value)- Check if string contains only alphanumeric characters
Decorators
Log
Method decorator to log execution:
@Log({ logArgs: true, logResult: true })
async findById(id: string) {
// Method implementation
}Options:
logArgs- Log method arguments (default: true)logResult- Log method result (default: true)
Utilities
DateUtils
Date manipulation utilities:
DateUtils.formatIsoDate(date)- Format date to ISO string without millisecondsDateUtils.startOfDay(date)- Get the start of the dayDateUtils.endOfDay(date)- Get the end of the dayDateUtils.isBetween(date, start, end)- Check if date is between two datesDateUtils.addDays(date, days)- Add days to a date
ObjectUtils
Object manipulation utilities:
ObjectUtils.removeNullish(obj)- Remove null and undefined valuesObjectUtils.isEmpty(obj)- Check if object is emptyObjectUtils.deepClone(obj)- Deep clone an objectObjectUtils.pick(obj, keys)- Pick specific propertiesObjectUtils.omit(obj, keys)- Omit specific properties
Configuration Validation
ConfigValidator
Service to validate NestJS configuration on application startup:
// Inject ConfigValidator in your module
@Module({
imports: [ConfigModule.forRoot()],
providers: [ConfigValidator],
})
export class AppModule {}
// Use in a service
@Injectable()
export class AppService implements OnModuleInit {
constructor(private readonly configValidator: ConfigValidator) {}
onModuleInit() {
// This will throw an error if required config is missing
this.configValidator.validateConfig([
{ key: 'DATABASE_URL', required: true },
{
key: 'PORT',
validator: (value) => parseInt(value, 10) > 0,
errorMessage: 'PORT must be a positive number'
},
]);
}
}ConfigSchema
Helper to create predefined configuration schemas:
// Use with NestJS ConfigModule
@Module({
imports: [
ConfigModule.forRoot({
validate: ConfigSchema.createValidator(
ConfigSchema.commonValidators(),
ConfigSchema.databaseValidators(),
ConfigSchema.jwtValidators()
)
})
]
})
export class AppModule {}Available schemas:
ConfigSchema.commonValidators()- Common environment variables (NODE_ENV, PORT)ConfigSchema.databaseValidators()- Database configurationConfigSchema.jwtValidators()- JWT authentication configurationConfigSchema.redisValidators()- Redis configurationConfigSchema.awsValidators()- AWS configurationConfigSchema.compose(...validators)- Combine multiple validatorsConfigSchema.createValidator(...validators)- Create a validator function for ConfigModule
Slack Notifications
SlackService
Service for sending notifications to Slack:
// Import the module in your application
@Module({
imports: [
NotificationsModule.register(),
// Or register it globally
// NotificationsModule.registerGlobal(),
],
})
export class AppModule {}
// Inject and use the service
@Injectable()
export class YourService {
constructor(private readonly slackService: SlackService) {}
async doSomething() {
try {
// Your code here
} catch (error) {
// Send detailed error notification to Slack
await this.slackService.sendErrorNotification({
error,
context: 'YourService.doSomething',
metadata: { userId: '123', operation: 'important-action' },
severity: 'high',
notification: {
channel: 'errors',
mentionUsers: ['U123ABC'], // User IDs to mention
mentionGroups: ['S456DEF'], // Group IDs to mention
mentionEveryone: false, // Whether to mention @channel
},
});
}
}
}Configuration:
SLACK_WEBHOOK_URL- Webhook URL for Slack integrationSLACK_DEFAULT_CHANNEL- Default channel for notifications (default: 'alerts')DEPLOYMENT_ENV- Environment name for better context in notificationsAPP_NAME- Application name for better context in notifications
The notification includes:
- Error message and stack trace
- Context of where the error occurred
- Environment and severity level
- Timestamp and unique error ID
- User ID if provided
- Custom metadata
- Color-coded based on severity
- Formatted for readability with sections and fields
Severity levels:
low(green) - Non-critical issuesmedium(amber) - Default, moderately important issueshigh(red) - Critical issues that need immediate attentioncritical(purple) - Highest priority issues
Contributing
We welcome contributions! Please see our contributing guide for details.
Commit Message Format
This repository follows Conventional Commits:
feat: A new featurefix: A bug fixdocs: Documentation only changesstyle: Changes that do not affect the meaning of the coderefactor: A code change that neither fixes a bug nor adds a featureperf: A code change that improves performancetest: Adding missing tests or correcting existing testsbuild: Changes that affect the build system or external dependenciesci: Changes to our CI configuration files and scriptschore: Other changes that don't modify src or test filesrevert: Reverts a previous commit
Example: feat(http): add new response formatter
CI/CD Pipeline
This project uses GitHub Actions for continuous integration and deployment:
- Streamlined Process: Direct pushes to
mainbranch trigger the complete CI/CD pipeline - Code Quality: Linting and formatting checks ensure consistent code style
- Testing: Comprehensive test suite ensures code reliability
- Automated Releases: Semantic versioning with automatic CHANGELOG generation based on commit messages
- Documentation: Automatic API documentation generation and deployment to GitHub Pages
For detailed information on setting up and troubleshooting the CI/CD pipeline, see GitHub Actions Setup Guide.
License
MIT