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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@gauravsharmacode/user-repository

v1.0.11

Published

Repository Package for user service - Database access layer with Prisma

Readme

@gauravsharmacode/user-repository

Database access layer for the User Service using Prisma ORM. This package provides repository pattern implementation with type-safe database operations and automatic Prisma client generation.

📦 Installation

npm install @gauravsharmacode/user-repository

🏗️ Architecture

This package depends on user-model and provides data access:

user-model (base package)
    ↓
user-repository (depends on user-model + Prisma) ← You are here
    ↓  
user-core (depends on user-model + user-repository)
    ↓
user-api (depends on user-core)

🔧 Key Features

  • Prisma ORM Integration: Type-safe database operations
  • Multi-platform Binary Support: Works on Debian, Alpine, and Windows
  • Automatic Client Generation: Prisma client auto-generated on install
  • Repository Pattern: Clean abstraction for data access
  • Production Ready: Optimized for containerized deployments

// Create session const session = await sessionRepo.create({ userId: user.id, refreshToken: 'token123', expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) });


## 🏗️ Structure

src/ ├── repositories/ # Repository classes │ ├── base.repository.ts │ ├── user.repository.ts │ ├── session.repository.ts │ └── index.ts ├── utils/ # Database utilities │ └── database.util.ts ├── index.ts prisma/ ├── schema.prisma # Database schema └── migrations/ # Migration files


## 🎯 Key Features

### Repository Pattern
- Clean separation of data access logic
- Consistent interface across all repositories
- Transaction support for complex operations
- Pagination support with metadata

### Type Safety
- Fully typed database operations
- Inferred types from Prisma schema
- Compile-time type checking
- Runtime type validation

### Advanced Queries
- Complex filtering and searching
- Role-based data inclusion
- Optimized query performance
- Pagination with count

## 🗃️ Database Schema

### Core Models
- **User**: Base user information
- **Admin, Driver, Rider, Manager, Vendor**: Role-specific data
- **Session**: Authentication sessions
- **PasswordResetToken**: Password reset tokens
- **EmailVerificationToken**: Email verification tokens

### Relationships
- One-to-one relationships between User and role-specific models
- Proper foreign key constraints
- Cascade delete for data integrity

## 📚 API Reference

### UserRepository

```typescript
class UserRepository {
  // CRUD Operations
  create(userData: CreateUserDto): Promise<User>
  findById(id: string): Promise<User | null>
  findByEmail(email: string): Promise<User | null>
  update(id: string, data: UpdateUserDto): Promise<User>
  
  // Role-specific operations
  findByIdWithRole(id: string): Promise<UserWithRole | null>
  createDriverData(data: DriverData): Promise<Driver>
  createVendorData(data: VendorData): Promise<Vendor>
  
  // Bulk operations
  findAll(options: PaginationOptions): Promise<PaginatedResult<User>>
  search(query: string, options: PaginationOptions): Promise<PaginatedResult<User>>
  
  // Status management
  updateStatus(id: string, status: UserStatus): Promise<User>
  updateRole(id: string, role: UserRole): Promise<User>
  softDelete(id: string): Promise<User>
  restore(id: string): Promise<User>
  
  // Statistics
  getStats(): Promise<UserStats>
}

SessionRepository

class SessionRepository {
  create(sessionData: SessionData): Promise<Session>
  findByRefreshToken(token: string): Promise<Session | null>
  findByUserId(userId: string): Promise<Session[]>
  update(id: string, data: Partial<Session>): Promise<Session>
  delete(id: string): Promise<Session>
  deleteByRefreshToken(token: string): Promise<Session>
  deleteAllByUserId(userId: string): Promise<{ count: number }>
  deleteExpired(): Promise<{ count: number }>
  isValid(token: string): Promise<boolean>
}

BaseRepository

abstract class BaseRepository {
  protected transaction<T>(fn: TransactionFn<T>): Promise<T>
  protected exists(model: string, id: string): Promise<boolean>
  protected getPaginationParams(page: number, limit: number): PaginationParams
  protected createPaginationMeta(total: number, page: number, limit: number): PaginationMeta
}

🔧 Database Setup

Environment Configuration

DATABASE_URL="postgresql://username:password@localhost:5432/database"

Migration Commands

# Generate Prisma client
npx prisma generate

# Run migrations
npx prisma migrate dev

# Deploy migrations
npx prisma migrate deploy

# Reset database
npx prisma migrate reset

# View database
npx prisma studio

🚀 Development

Build Commands

npm run build    # Build TypeScript
npm run dev      # Watch mode
npm run clean    # Clean build files

Database Commands

npm run db:generate  # Generate Prisma client
npm run db:migrate   # Run migrations
npm run db:deploy    # Deploy migrations
npm run db:studio    # Open Prisma Studio

🔗 Dependencies

Production

  • @prisma/client: Database client
  • user-model: Shared type definitions

Development

  • prisma: Database toolkit
  • typescript: Type checking

🎯 Performance

Optimizations

  • Connection pooling
  • Query optimization
  • Selective field loading
  • Pagination with efficient counting
  • Indexed database queries

Monitoring

  • Query performance tracking
  • Connection pool monitoring
  • Error logging and metrics

🔒 Security

Data Protection

  • Parameterized queries (SQL injection prevention)
  • Input validation
  • Soft deletes for data retention
  • Audit trail support

Access Control

  • Repository-level access control
  • Transaction isolation
  • Connection security