Skip to content

Latest commit

 

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Shelfy Logo

Shelfy - Backend API

The powerful RESTful server-side engine for the Shelfy Library Management System, built with Node.js, Express and MongoDB.

Client Repo GitHub Repo Node.js Express TypeScript MongoDB


🔍 Backend Overview

Shelfy Backend is a production-ready API that serves as the core engine for the Shelfy ecosystem. It handles complex book inventory management and borrowing workflows with strict business logic enforcement and robust data validation.

This repository focuses exclusively on the Server-Side logic, providing a high-performance RESTful API for the Shelfy Client-Side Application.


✨ Key Features

📚 Book Management

FeatureDescription
CRUD OperationsCreate, read, update and delete books with full validation
Genre FilteringFilter books by FICTION, NON_FICTION, SCIENCE, HISTORY, BIOGRAPHY, FANTASY
Advanced SortingSort by any field in ascending or descending order with pagination
Unique ISBNEnforces unique ISBN per book to prevent duplicate entries

🔄 Borrowing System

FeatureDescription
Availability ControlAuto-updates book availability when all copies are borrowed
Copy ManagementTracks exact copy count and prevents over-borrowing
Due Date ValidationEnforces future-only due dates on every borrow request
Borrow SummaryAggregated view of all borrowed books with total quantities

🛡️ Quality & Reliability

FeatureDescription
Zod ValidationStrong schema-level validation with detailed error messages
Global Error HandlerCentralized middleware for consistent, structured error responses
Mongoose MiddlewarePre-save hooks for automatic availability management
Static MethodsReusable Mongoose static method for complex borrow logic

🛠️ Tech Stack

TechnologyVersionPurpose
Node.jsLTSJavaScript runtime environment
Express.js^5.1.0Web framework and routing
TypeScript^5.8.3Type-safe JavaScript superset
MongoDB^6.17.0NoSQL document database
Mongoose^8.16.2MongoDB ODM with schema validation
Zod^4.0.3Runtime schema validation
CORS^2.8.5Cross-origin resource sharing
dotenv^17.2.0Environment variable management
ts-node-dev^2.0.0TypeScript live-reload dev server

🏗️ Architecture

                            ┌──────────────────────────────────────────────────┐
                            │                   Client Request                 │
                            └───────────────────────┬──────────────────────────┘
                                                    │
                            ┌───────────────────────▼──────────────────────────┐
                            │              Express Application                 │
                            │         (CORS · JSON Parser · Routes)            │
                            └──────────┬────────────────────────┬──────────────┘
                                       │                        │
                            ┌──────────▼──────────┐  ┌──────────▼───────────────┐
                            │   /api/books        │  │   /api/borrow            │
                            │   Book Router       │  │   Borrow Router          │
                            └──────────┬──────────┘  └──────────┬───────────────┘
                                       │                        │
                            ┌──────────▼────────────────────────▼───────────────┐
                            │              Controllers (Zod Validation)         │
                            └──────────────────────────┬────────────────────────┘
                                                       │
                            ┌──────────────────────────▼────────────────────────┐
                            │         Mongoose Models (Static Methods,          │
                            │         Pre-save Middleware, Aggregation)         │
                            └──────────────────────────┬────────────────────────┘
                                                       │
                            ┌──────────────────────────▼────────────────────────┐
                            │                    MongoDB Atlas                  │
                            └───────────────────────────────────────────────────┘

📂 Project Structure

milestone-16-server/
├── src/
│   ├── app/
│   │   ├── controllers/        # Route handler logic
│   │   ├── interfaces/         # TypeScript type definitions
│   │   ├── models/             # Mongoose schemas & static methods
│   │   ├── middlewares/        # Global error & 404 handlers
│   │   └── zodSchemas/         # Zod validation schemas
│   ├── app.ts                  # Express app setup
│   └── server.ts               # Entry point & DB connection
├── .env                        # Environment variables
├── package.json
└── README.md

🚀 Getting Started

Prerequisites

RequirementDetails
Node.jsv18 or higher
MongoDBAtlas account or local installation
Package Managernpm or yarn

Installation

  1. Clone the repository

    git clone https://github.com/zahid-official/milestone-16-shelfyServer.git
    cd milestone-16-server
  2. Install dependencies

    npm install
  3. Configure environment variables

    Create a .env file in the root directory:

    PORT=3000
    DB_USER=your_mongodb_username
    DB_PASSWORD=your_mongodb_password
    DB_NAME=your_database_name
  4. Start the development server

    npm run dev

    The server will start on http://localhost:3000


🔑 Environment Variables

VariableDescriptionRequired
PORTServer port (default: 3000)No
DB_USERMongoDB Atlas usernameYes
DB_PASSWORDMongoDB Atlas passwordYes
DB_NAMETarget MongoDB database nameYes

📜 Available Scripts

ScriptCommandDescription
Developmentnpm run devStart server with live reload via ts-node-dev
Testnpm testRun test suite

⚙️ API Reference

Response Format

All API responses share a consistent structure:

{
  "success": true,
  "message": "Operation successful",
  "data": {}
}

📖 Books Endpoints

MethodEndpointDescription
GET/api/booksGet all books (supports filter, sort, limit)
GET/api/books/:bookIdGet a single book by ID
POST/api/booksCreate a new book
PUT/api/books/:bookIdUpdate an existing book
DELETE/api/books/:bookIdDelete a book

Query Parameters for GET /api/books:

  • filter - Genre filter: FICTION | NON_FICTION | SCIENCE | HISTORY | BIOGRAPHY | FANTASY
  • sortBy - Field to sort by (default: createdAt)
  • sort - Order: asc or desc (default: asc)
  • limit - Number of results (default: 10)

🔄 Borrow Endpoints

MethodEndpointDescription
GET/api/borrowGet aggregated borrowed books summary
POST/api/borrowBorrow a book (enforces availability & copy count)

🌟 How It Works

Borrow Flow:

                                       Client POST /api/borrow
                                                  │
                                                  ▼
                              Zod validates { book, quantity, dueDate }
                                                  │
                                                  ▼
                                BorrowModel.borrowBook() static method
                                                  │
                                            ┌─────┴──────┐
                                            │            │
                                            ▼            ▼
                                    Book exists?  Enough copies?
                                            │            │
                                            └─────┬──────┘
                                                  │ Yes
                                                  ▼
                                      Deduct copies from book
                                                  │
                                                  ▼
                              Pre-save hook sets available = (copies > 0)
                                                  │
                                                  ▼
                                Save borrow record → Return 201 response
  1. Request received - Zod validates all fields including future-date enforcement
  2. Static method invoked - BorrowModel.borrowBook() handles the complete workflow
  3. Availability checked - Ensures sufficient copies are available before proceeding
  4. Copy count updated - Deducts borrowed quantity from the book document
  5. Middleware fires - Pre-save hook automatically recalculates the available flag
  6. Borrow record saved - Returns the new borrow document with a 201 status

🌟 Author

Zahid Official

Zahid Official

Web Developer | Tech Enthusiast

GitHub LinkedIn Email

Crafting robust, type-safe APIs and clean architectural solutions.


🤝 Contributing

# 1. Fork the repository on GitHub

# 2. Clone your fork
git clone https://github.com/your-username/milestone-16-server.git

# 3. Create a feature branch
git checkout -b feature/your-feature-name

# 4. Commit your changes
git commit -m "feat: add your feature description"

# 5. Push to your fork
git push origin feature/your-feature-name

# 6. Open a Pull Request on GitHub

Shelfy - Your books, managed with precision.

About

Shelfy’s backend is the high-performance RESTful engine driving the Shelfy Library Management System. Built with Node.js, Express, and MongoDB using TypeScript, it manages book inventory and borrowing workflows with strict business logic and robust validation for a reliable library solution.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages