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 Application: View Live App
- π Source Code: GitHub Repository
- π 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
- Runtime: Node.js
- Framework: Express.js
- Language: TypeScript
- Database: MongoDB with Mongoose ODM
- Middleware: CORS, dotenv
- Development: ts-node-dev, TypeScript compiler
| 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 |
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/borrow |
Borrow books |
GET |
/api/borrow |
Get borrowing summary with aggregation |
DELETE |
/api/borrow/:borrowId |
Cancel borrowing (middleware demo) |
The books endpoint supports advanced querying:
GET /api/books?filter=GENRE&sortBy=createdAt&sort=asc|desc&limit=5
filter: Filter by genresortBy: Sort field (e.g.,createdAt,title,author)sort: Sort order (ascordesc)limit: Number of results per page
- 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
- 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
findByGenre(genre): Find all available books by genrefindAvailableBooks(): Find all currently available books
updateAvailability(): Updates book availability based on current copies
{
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
}{
book: ObjectId, // Reference to book
quantity: number, // Number of copies borrowed
dueDate: Date // Return due date
}Valid genres: FICTION, NON_FICTION, SCIENCE, HISTORY, BIOGRAPHY, FANTASY
- 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
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
}POST /api/borrow
Content-Type: application/json
{
"book": "64ab3f9e2a4b5c6d7e8f9012",
"quantity": 2,
"dueDate": "2025-07-18T00:00:00.000Z"
}GET /api/books/genre/SCIENCEDELETE /api/borrow/64bc4a0f9e1c2d3f4b5a6789GET /api/books?filter=SCIENCE&sortBy=title&sort=asc&limit=10The 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
}
}
}
}- Node.js (v16 or higher)
- MongoDB instance
- npm or yarn package manager
-
Clone the repository
git clone https://github.com/AyshaUrmi0/Assignment3.git cd Assignment3 -
Install dependencies
npm install
-
Environment Configuration
Create a
.envfile in the root directory:PORT=5000 MONGO_URI=mongodb://localhost:27017/library-api NODE_ENV=development
-
Start the development server
npm run dev
The API will be available at
http://localhost:5000
npm run build
npm start| 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) |
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
- 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
- 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
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Aysha Urmi - GitHub Profile
β Star this repository if you find it helpful!