1.0.0 โข Published 5 months ago
@gotocva/nestjs-utils v1.0.0
๐ @gotocva/nestjs-utils
A reusable utility library for NestJS applications. This package includes cryptographic helpers, JWT handling, global exception filtering, response interceptors, and more.
๐ฆ Features
- ๐ AES-256-CBC encryption/decryption
- ๐ JWT token generation, verification, and decoding
- โ ๏ธ Global exception handler with MongoDB error awareness
- ๐ฆ Standardized API response formatting
- ๐งพ SHA-256 hashing utilities
๐ฆ Installation
npm install @gotocva/nestjs-utils
Or via GitHub:
npm install git+https://github.com/your-org/nestjs-utils.git
Ensure you have
@nestjs/jwt
and@nestjs/common
installed.
๐ง Usage
1. Crypto Utilities
import { createTransactionHash, createContractAddress, encrypt, decrypt } from '@gotocva/nestjs-utils';
// Hashing
const txHash = createTransactionHash({ sender: 'alice', amount: 100 });
const contractAddr = createContractAddress('SomeContractIdentifier');
// Encryption/Decryption
const key = crypto.randomBytes(32); // Or load from config
const encrypted = encrypt('my-secret-data', key);
const decrypted = decrypt(encrypted, key);
2. JWT Handler
import { JwtHandler } from '@gotocva/nestjs-utils';
import { JwtService } from '@nestjs/jwt';
const jwtHandler = new JwtHandler(new JwtService({ secret: process.env.JWT_SECRET }));
const token = jwtHandler.generateToken({ userId: 123 });
const verified = jwtHandler.verifyToken(token);
const decoded = jwtHandler.decodeToken(token);
3. Global Exception Filter
import { ExceptionHandler } from '@gotocva/nestjs-utils';
import { APP_FILTER } from '@nestjs/core';
@Module({
providers: [
{
provide: APP_FILTER,
useClass: ExceptionHandler,
},
],
})
export class AppModule {}
Handles:
- Mongoose validation errors
- MongoDB error codes (duplicate key, validation, unauthorized, etc.)
- Custom
HttpException
4. Response Interceptor
import { ResponseInterceptor } from '@gotocva/nestjs-utils';
import { APP_INTERCEPTOR } from '@nestjs/core';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: ResponseInterceptor,
},
],
})
export class AppModule {}
All HTTP responses will follow a consistent format:
{
"message": "Success message",
"status": true,
"result": { /* your data */ },
"error": null,
"timestamps": "2025-05-11T00:00:00.000Z",
"status_code": 200,
"path": "/api/example"
}
๐ Configuration
- Set
JWT_SECRET
in your environment variables for theJwtHandler
. - AES encryption keys must be 32 bytes for
aes-256-cbc
.
๐งช Testing
To test the utility functions independently:
npm run test
Add test coverage for each utility as needed.
๐งโ๐ป Contributing
- Fork the repository
- Create your feature branch:
git checkout -b feature/my-utils
- Commit your changes
- Push to the branch
- Open a Pull Request
๐ License
MIT License ยฉ Sivabharathy
1.0.0
5 months ago