Skip to content

Latest commit

Β 

History

7 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“š Library Management API

A robust and scalable Library Management System API built with Express.js, TypeScript, and MongoDB (Mongoose). This API provides comprehensive book management, borrowing operations, and advanced analytics using MongoDB aggregation pipelines.

πŸš€ Live Demo

✨ Key Features

  • πŸ“– Book Management: Complete CRUD operations for books
  • πŸ”„ Borrowing System: Intelligent book borrowing with business logic validation
  • πŸ“Š Analytics: Advanced borrowing statistics using MongoDB aggregation
  • πŸ” Search & Filter: Comprehensive filtering, sorting, and pagination
  • βœ… Validation: Robust schema validation with Mongoose
  • πŸ”§ Middleware: Custom pre/post hooks for business logic
  • πŸ“š Methods: Mongoose static and instance methods
  • 🚨 Error Handling: Comprehensive error handling and user feedback
  • πŸ”„ Automatic Updates: Smart availability management and copy tracking

πŸ›  Technology Stack

  • Runtime: Node.js
  • Framework: Express.js
  • Language: TypeScript
  • Database: MongoDB with Mongoose ODM
  • Middleware: CORS, dotenv
  • Development: ts-node-dev, TypeScript compiler

πŸ“‹ API Endpoints

πŸ“š Book Management

Method Endpoint Description
POST /api/books Create a new book
GET /api/books Get all books with filtering & pagination
GET /api/books/genre/:genre Get books by specific genre (static method demo)
GET /api/books/:bookId Get book by ID
PUT /api/books/:bookId Update book information
DELETE /api/books/:bookId Delete a book

πŸ“– Borrowing System

Method Endpoint Description
POST /api/borrow Borrow books
GET /api/borrow Get borrowing summary with aggregation
DELETE /api/borrow/:borrowId Cancel borrowing (middleware demo)

πŸ” Query Parameters

The books endpoint supports advanced querying:

GET /api/books?filter=GENRE&sortBy=createdAt&sort=asc|desc&limit=5
  • filter: Filter by genre
  • sortBy: Sort field (e.g., createdAt, title, author)
  • sort: Sort order (asc or desc)
  • limit: Number of results per page

πŸ”§ Advanced Features

Mongoose Middleware (Pre/Post Hooks)

Book Model Middleware

  • Pre-save Hook: Automatically updates book availability when copies change
  • Pre-validate Hook: Ensures ISBN uniqueness across all books
  • Post-save Hook: Logs book operations for monitoring

Borrow Model Middleware

  • Pre-save Hook: Validates book availability and due date before borrowing
  • Post-save Hook: Automatically updates book copies after successful borrowing
  • Post-remove Hook: Restores book copies when borrowing is cancelled

Mongoose Methods

Static Methods

  • findByGenre(genre): Find all available books by genre
  • findAvailableBooks(): Find all currently available books

Instance Methods

  • updateAvailability(): Updates book availability based on current copies

πŸ“ Data Models

Book Schema

{
  title: string,           // Book title
  author: string,          // Author name
  genre: BookGenre,        // Book genre
  isbn: string,            // Unique ISBN
  description: string,     // Book description
  copies: number,          // Available copies
  available: boolean       // Availability status
}

Borrow Schema

{
  book: ObjectId,          // Reference to book
  quantity: number,        // Number of copies borrowed
  dueDate: Date           // Return due date
}

βœ… Business Rules & Validation

Genre Constraints

Valid genres: FICTION, NON_FICTION, SCIENCE, HISTORY, BIOGRAPHY, FANTASY

Business Logic

  • ISBN must be unique across all books
  • Cannot borrow more copies than available
  • Book availability automatically updates when copies reach 0
  • Borrowing summary includes book title, ISBN, and total quantity
  • Due date must be in the future
  • Automatic copy restoration when borrowing is cancelled

πŸ§ͺ API Examples

Create a New Book

POST /api/books
Content-Type: application/json

{
  "title": "The Theory of Everything",
  "author": "Stephen Hawking",
  "genre": "SCIENCE",
  "isbn": "9780553380163",
  "description": "An overview of cosmology and black holes.",
  "copies": 5,
  "available": true
}

Borrow Books

POST /api/borrow
Content-Type: application/json

{
  "book": "64ab3f9e2a4b5c6d7e8f9012",
  "quantity": 2,
  "dueDate": "2025-07-18T00:00:00.000Z"
}

Get Books by Genre (Static Method Demo)

GET /api/books/genre/SCIENCE

Cancel Borrowing (Middleware Demo)

DELETE /api/borrow/64bc4a0f9e1c2d3f4b5a6789

Get Books with Filtering

GET /api/books?filter=SCIENCE&sortBy=title&sort=asc&limit=10

🚨 Error Handling

The API provides structured error responses:

{
  "message": "Validation failed",
  "success": false,
  "error": {
    "name": "ValidationError",
    "errors": {
      "copies": {
        "message": "Copies must be a positive number",
        "name": "ValidatorError",
        "kind": "min",
        "value": -5
      }
    }
  }
}

πŸš€ Getting Started

Prerequisites

  • Node.js (v16 or higher)
  • MongoDB instance
  • npm or yarn package manager

Installation

  1. Clone the repository

    git clone https://github.com/AyshaUrmi0/Assignment3.git
    cd Assignment3
  2. Install dependencies

    npm install
  3. Environment Configuration

    Create a .env file in the root directory:

    PORT=5000
    MONGO_URI=mongodb://localhost:27017/library-api
    NODE_ENV=development
  4. Start the development server

    npm run dev

    The API will be available at http://localhost:5000

Production Build

npm run build
npm start

πŸ“œ Available Scripts

Command Description
npm run dev Start development server with hot reload
npm run build Build TypeScript project
npm start Start production server
npm test Run test suite (not implemented)

πŸ— Project Structure

src/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ controllers/     # Request handlers
β”‚   β”œβ”€β”€ models/         # Mongoose schemas with middleware
β”‚   └── route/          # API routes
β”œβ”€β”€ config/             # Configuration files
β”œβ”€β”€ index.ts            # Application entry point
└── server.ts           # Server setup

πŸ”§ Development Features

  • TypeScript: Full type safety and modern JavaScript features
  • Hot Reload: Automatic server restart on file changes
  • MongoDB Aggregation: Advanced data processing and analytics
  • Middleware Hooks: Custom business logic integration
  • Static/Instance Methods: Mongoose method implementations
  • Automatic Validation: Pre/post save hooks for data integrity

πŸ“Š Performance Features

  • MongoDB Indexing: Optimized database queries
  • Aggregation Pipelines: Efficient data processing
  • Connection Pooling: Database connection optimization
  • Error Boundaries: Graceful error handling
  • Middleware Automation: Reduced manual validation code

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ‘¨β€πŸ’» Author

Aysha Urmi - GitHub Profile


⭐ Star this repository if you find it helpful!

About

A robust and scalable Library Management System API built with Express.js, TypeScript, and MongoDB (Mongoose). This API provides comprehensive book management, borrowing operations, and advanced analytics using MongoDB aggregation pipelines.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages