pulse-shared
v1.0.8
Published
Shared utilities and base classes for microservices
Maintainers
Readme
Shared Package
A comprehensive shared package for building scalable NestJS applications with proper error handling, logging, and database operations.
📁 Project Structure
shared-package/
├── src/
│ ├── core/ # Core base classes and interfaces
│ │ ├── base/ # Base classes (Repository, Service, Controller)
│ │ ├── interfaces/ # Core interfaces
│ │ └── decorators/ # Core decorators
│ ├── types/ # Type definitions
│ │ ├── common/ # Common types (BaseEntity, Id, etc.)
│ │ ├── database/ # Database-specific types
│ │ └── auth/ # Authentication types
│ ├── config/ # Configuration classes
│ │ ├── database/ # Database configuration
│ │ ├── auth/ # Auth configuration
│ │ └── logging/ # Logging configuration
│ ├── utils/ # Utility functions
│ │ ├── helpers/ # Helper utilities
│ │ ├── validators/ # Validation utilities
│ │ └── decorators/ # Utility decorators
│ ├── testing/ # Testing utilities
│ │ ├── unit/ # Unit test utilities
│ │ ├── integration/ # Integration test utilities
│ │ └── fixtures/ # Test fixtures
│ ├── examples/ # Usage examples
│ │ ├── repositories/ # Repository examples
│ │ ├── services/ # Service examples
│ │ └── controllers/ # Controller examples
│ └── documentation/ # Documentation
│ ├── api/ # API documentation
│ └── guides/ # Usage guides
├── package.json
├── tsconfig.json
└── README.md🚀 Quick Start
Installation
npm install @your-org/shared-packageBasic Usage
1. Create a Repository
import { Injectable, Inject } from '@nestjs/common';
import { BaseRepository } from '@your-org/shared-package';
import { users } from './schema'; // Your Drizzle schema
@Injectable()
export class UserRepository extends BaseRepository<User, typeof users> {
constructor(@Inject('DATABASE') db: DrizzleDatabase) {
super('UserRepository', db, users);
}
}2. Create a Service
import { Injectable } from '@nestjs/common';
import { BaseCrudService } from '@your-org/shared-package';
import { UserRepository } from './user.repository';
@Injectable()
export class UserService extends BaseCrudService<User> {
constructor(private readonly userRepository: UserRepository) {
super(userRepository);
}
}3. Create a Controller
import { Controller } from '@nestjs/common';
import { BaseCrudController } from '@your-org/shared-package';
import { UserService } from './user.service';
@Controller('users')
export class UserController extends BaseCrudController<User> {
constructor(private readonly userService: UserService) {
super(userService);
}
}📚 Core Modules
Core Base Classes
- BaseRepository: Generic repository with Drizzle ORM integration
- BaseService: Base service with common CRUD operations
- BaseCrudService: Extended service with bulk operations
- BaseController: Base controller with REST endpoints
- BaseRepositoryService: Service for database operations and logging
Types
- Common Types: BaseEntity, Id, ApiResponse, etc.
- Database Types: Drizzle-specific types and utilities
- Auth Types: Authentication and authorization types
Configuration
- Database Config: Database connection and settings
- Logging Config: Logging configuration and utilities
- Auth Config: Authentication configuration
Utilities
- Helpers: Async try-catch wrapper and other utilities
- Validators: Validation utilities and schemas
- Decorators: Custom decorators for dependency injection
🔧 Configuration
Database Configuration
import { DatabaseConfig } from '@your-org/shared-package';
const config: DatabaseConfig = {
host: 'localhost',
port: 5432,
database: 'myapp',
username: 'user',
password: 'password',
ssl: false
};Logging Configuration
import { RepositoryLoggingConfig } from '@your-org/shared-package';
const loggingConfig: RepositoryLoggingConfig = {
enabled: true,
logLevel: 'info',
logOperations: true,
logQueries: false,
logErrors: true,
includeParams: true,
sensitiveFields: ['password', 'token']
};🧪 Testing
Unit Tests
import { Test, TestingModule } from '@nestjs/testing';
import { UserRepository } from './user.repository';
describe('UserRepository', () => {
let repository: UserRepository;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UserRepository,
{
provide: 'DATABASE',
useValue: mockDatabase
}
]
}).compile();
repository = module.get<UserRepository>(UserRepository);
});
it('should be defined', () => {
expect(repository).toBeDefined();
});
});Integration Tests
import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';
import { UserRepository } from './user.repository';
describe('UserService Integration', () => {
let service: UserService;
let repository: UserRepository;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UserService, UserRepository]
}).compile();
service = module.get<UserService>(UserService);
repository = module.get<UserRepository>(UserRepository);
});
it('should create a user', async () => {
const userData = { name: 'John Doe', email: '[email protected]' };
const user = await service.create(userData);
expect(user).toBeDefined();
expect(user.name).toBe(userData.name);
});
});📖 API Documentation
Repository Methods
findById(id: Id): Find entity by IDfindAll(limit?, offset?): Find all entities with paginationcreate(data: Partial<T>): Create new entityupdate(id: Id, data: Partial<T>): Update entity by IDdelete(id: Id): Delete entity by IDexists(id: Id): Check if entity existsfindByField(field, value): Find entities by field valuefindOneByField(field, value): Find single entity by field valuecount(): Count total entities
Service Methods
- All repository methods plus:
bulkCreate(data[]): Create multiple entitiesbulkUpdate(ids[], data): Update multiple entitiesbulkDelete(ids[]): Delete multiple entities
Controller Endpoints
GET /:id: Get entity by IDGET /: Get all entities with paginationPOST /: Create new entityPUT /:id: Update entityDELETE /:id: Delete entityGET /count: Get total countPOST /bulk: Bulk createPUT /bulk: Bulk updateDELETE /bulk: Bulk delete
🔒 Error Handling
The package includes comprehensive error handling:
import { RepositoryErrorCode } from '@your-org/shared-package';
// Error codes
RepositoryErrorCode.RECORD_NOT_FOUND
RepositoryErrorCode.DUPLICATE_KEY
RepositoryErrorCode.VALIDATION_ERROR
RepositoryErrorCode.DATABASE_ERROR
RepositoryErrorCode.TRANSACTION_ERROR📝 Logging
Automatic logging for all operations:
// Logging is automatically enabled with configurable levels
const loggingConfig = {
enabled: true,
logLevel: 'info',
logOperations: true,
logQueries: false,
includeParams: true
};🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
📄 License
MIT License - see LICENSE file for details
🆘 Support
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Review the examples
