npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

pulse-shared

v1.0.8

Published

Shared utilities and base classes for microservices

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-package

Basic 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 ID
  • findAll(limit?, offset?): Find all entities with pagination
  • create(data: Partial<T>): Create new entity
  • update(id: Id, data: Partial<T>): Update entity by ID
  • delete(id: Id): Delete entity by ID
  • exists(id: Id): Check if entity exists
  • findByField(field, value): Find entities by field value
  • findOneByField(field, value): Find single entity by field value
  • count(): Count total entities

Service Methods

  • All repository methods plus:
  • bulkCreate(data[]): Create multiple entities
  • bulkUpdate(ids[], data): Update multiple entities
  • bulkDelete(ids[]): Delete multiple entities

Controller Endpoints

  • GET /:id: Get entity by ID
  • GET /: Get all entities with pagination
  • POST /: Create new entity
  • PUT /:id: Update entity
  • DELETE /:id: Delete entity
  • GET /count: Get total count
  • POST /bulk: Bulk create
  • PUT /bulk: Bulk update
  • DELETE /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

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. 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