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

@gauravsharmacode/user-api

v1.0.5

Published

API Package for user service

Readme

@gauravsharmacode/user-api

HTTP API layer for the User Service built with Express.js. This package provides a complete REST API with authentication, validation, rate limiting, and structured logging.

📦 Installation

npm install @gauravsharmacode/user-api

🏗️ Architecture

This package provides the HTTP API layer and depends on all other packages:

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

🔧 Key Features

  • Express.js REST API: Full HTTP API with proper status codes
  • API-Layer Validation: Zod schemas for request/response validation
  • JWT Authentication: Secure token-based authentication
  • Rate Limiting: Protection against API abuse
  • Structured Logging: JSON logs with @gauravsharmacode/neat-logger
  • Security Headers: Helmet.js for security best practices
  • CORS Support: Configurable cross-origin resource sharing
  • Health Checks: Built-in health monitoring endpoints
  • Docker Ready: Containerized deployment support
src/
├── controllers/          # Request handlers
│   ├── auth.controller.ts
│   ├── user.controller.ts
│   ├── admin.controller.ts
│   └── index.ts
├── middleware/           # Express middleware
│   ├── auth.middleware.ts
│   ├── validation.middleware.ts
│   ├── error.middleware.ts
│   └── index.ts
├── routes/              # Route definitions
│   ├── auth.routes.ts
│   ├── user.routes.ts
│   ├── admin.routes.ts
│   └── index.ts
├── types/               # API-specific types
│   └── express.d.ts
├── app.ts              # Express app configuration
└── index.ts           # Server entry point

🚀 API Endpoints

Authentication

POST   /api/auth/register         # User registration
POST   /api/auth/login           # User login
POST   /api/auth/logout          # User logout
POST   /api/auth/refresh         # Refresh access token
POST   /api/auth/forgot-password # Initiate password reset
POST   /api/auth/reset-password  # Complete password reset

User Profile

GET    /api/users/me             # Get current user profile
PUT    /api/users/me             # Update profile
PATCH  /api/users/me/password    # Change password
DELETE /api/users/me             # Delete account

Admin Operations

GET    /api/admin/users          # List users (paginated)
GET    /api/admin/users/:id      # Get user by ID
PATCH  /api/admin/users/:id/status   # Update user status
PATCH  /api/admin/users/:id/role     # Update user role
DELETE /api/admin/users/:id      # Delete user
POST   /api/admin/users/bulk     # Bulk operations
GET    /api/admin/users/stats    # User statistics

Role-specific Registration

POST   /api/auth/register/driver   # Driver registration
POST   /api/auth/register/vendor   # Vendor registration
POST   /api/auth/register/manager  # Manager registration
POST   /api/auth/register/admin    # Admin registration

🔧 Configuration

Environment Variables

# Server Configuration
PORT=3000
NODE_ENV=development

# CORS Configuration
CORS_ORIGIN=http://localhost:3000
CORS_METHODS=GET,POST,PUT,DELETE,PATCH

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000  # 15 minutes
RATE_LIMIT_MAX_REQUESTS=100  # requests per window

# API Configuration
API_VERSION=v1
API_PREFIX=/api

Middleware Configuration

import { app } from './app';

// Configure CORS
app.use(cors({
  origin: process.env.CORS_ORIGIN,
  credentials: true
}));

// Configure rate limiting
app.use(rateLimit({
  windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS),
  max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS)
}));

📚 API Reference

Request/Response Examples

User Registration

POST /api/auth/register
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "SecurePass123!",
  "firstName": "John",
  "lastName": "Doe",
  "role": "RIDER"
}
{
  "success": true,
  "data": {
    "user": {
      "id": "user123",
      "email": "[email protected]",
      "firstName": "John",
      "lastName": "Doe",
      "role": "RIDER",
      "status": "PENDING"
    },
    "message": "Registration successful"
  }
}

User Login

POST /api/auth/login
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "SecurePass123!"
}
{
  "success": true,
  "data": {
    "user": {
      "id": "user123",
      "email": "[email protected]",
      "firstName": "John",
      "lastName": "Doe",
      "role": "RIDER"
    },
    "tokens": {
      "accessToken": "eyJhbGciOiJIUzI1NiIs...",
      "refreshToken": "dGhpcyBpcyBhIHJlZnJl...",
      "expiresIn": 900
    }
  }
}

Error Responses

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format"
      }
    ]
  }
}

🛡️ Security Features

Authentication

  • JWT token-based authentication
  • Refresh token rotation
  • Session management
  • Password security validation

Authorization

  • Role-based access control (RBAC)
  • Resource-level permissions
  • Admin privilege checks
  • Route protection

Input Validation

  • Request schema validation
  • Input sanitization
  • SQL injection prevention
  • XSS protection

Rate Limiting

  • Per-IP rate limiting
  • Endpoint-specific limits
  • Burst protection
  • DDoS mitigation

🚀 Development

Start Development Server

npm run dev     # Start with hot reload
npm run start   # Start production server
npm run build   # Build for production

Testing

npm test              # Run tests
npm run test:watch    # Watch mode
npm run test:e2e      # End-to-end tests

🔗 Dependencies

Production

  • user-core: Business logic layer
  • express: Web framework
  • cors: Cross-origin resource sharing
  • helmet: Security middleware
  • compression: Response compression
  • express-rate-limit: Rate limiting

Development

  • typescript: Type checking
  • nodemon: Development server
  • @types/express: Express type definitions

🐳 Docker Support

Dockerfile

FROM node:18-alpine

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

EXPOSE 3000
CMD ["npm", "start"]

Docker Compose

version: '3.8'
services:
  user-api:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=postgresql://...
      - JWT_SECRET=...
    depends_on:
      - postgres

📊 Monitoring

Health Checks

GET /api/health         # Basic health check
GET /api/health/ready   # Readiness probe
GET /api/health/live    # Liveness probe

Metrics

  • Request/response times
  • Error rates
  • Active sessions
  • Database connection status

🚨 Error Handling

Error Types

  • 400: Bad Request (validation errors)
  • 401: Unauthorized (authentication required)
  • 403: Forbidden (insufficient permissions)
  • 404: Not Found (resource not found)
  • 409: Conflict (duplicate resource)
  • 429: Too Many Requests (rate limited)
  • 500: Internal Server Error

Error Response Format

{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "details": {}, // Additional error context
    "timestamp": "2023-10-11T12:00:00Z",
    "path": "/api/users/me"
  }
}