@slickteam/nestjs-utils
v1.4.1
Published
Utils functions and classes for Nestjs
Readme
Slick NestJS Utils
Utility functions for NestJS applications, providing logging decorators and error handling helpers.
Installation
npm install @slickteam/nestjs-utilsAPI Reference
LoggerParams
Method decorator that automatically logs function parameters when called.
import { LoggerParams } from '@slickteam/nestjs-utils';
class UserService {
@LoggerParams() // Default: 'verbose' level
findUser(id: string, options: object) {
// Logs: "findUser([0]=123,[1]={...})" at verbose level
}
@LoggerParams('debug')
createUser(name: string) {
// Logs: "createUser([0]="John")" at debug level
}
@LoggerParams({
level: 'debug',
paramNames: ['userId', 'userData'],
})
updateUser(id: string, data: object) {
// Logs: "updateUser(userId="123", userData={...})" at debug level
}
}Parameters:
level(optional): Log level -'verbose'|'debug'|'log'|'warn'|'error'. Default:'verbose'paramNames(optional): Array of parameter names to use instead of indices. If provided, must match the number of parameters.
Note: You can pass either a string for the log level, or an options object with
levelandparamNamesproperties.
throwErrorAndLog
Throws an HttpException and logs the error message.
import { HttpStatus, Logger } from '@nestjs/common';
import { throwErrorAndLog } from '@slickteam/nestjs-utils';
class UserService {
private readonly logger = new Logger(UserService.name);
findUser(id: string) {
const user = this.repository.find(id);
if (!user) {
throwErrorAndLog('User not found', HttpStatus.NOT_FOUND, this.logger);
}
return user;
}
}Parameters:
message: Error message to log and throwtypeError(optional): HTTP status code. Default:HttpStatus.INTERNAL_SERVER_ERRORlogger(optional): Logger instance. If not provided, uses the staticLogger
throwErrorAndLogWithContext
Throws an HttpException and logs the error message with a context string.
import { HttpStatus } from '@nestjs/common';
import { throwErrorAndLogWithContext } from '@slickteam/nestjs-utils';
function validateInput(data: unknown) {
if (!data) {
throwErrorAndLogWithContext('Invalid input', HttpStatus.BAD_REQUEST, 'ValidationService');
}
}Parameters:
message: Error message to log and throwtypeError(optional): HTTP status code. Default:HttpStatus.INTERNAL_SERVER_ERRORcontext(optional): Context string for the logger
logLevel
Returns an array of log levels to enable, based on a minimum level (cascade).
import { logLevel } from '@slickteam/nestjs-utils';
// Returns ['debug', 'log', 'warn', 'error']
const levels = logLevel('debug');
// Usage with NestJS bootstrap
const app = await NestFactory.create(AppModule, {
logger: logLevel('debug'),
});Parameters:
level: Minimum log level -'verbose'|'debug'|'log'|'warn'|'error'
Returns: Array of LogLevel including the specified level and all levels above it.
Requirements
- Node.js >= 18
- NestJS >= 11
