An open API service indexing awesome lists of open source software.

https://github.com/maksudulhaque2000/assignment-3-l2

A robust Library Management API built with Node.js, Express, TypeScript, and MongoDB (Mongoose). Features CRUD for books, borrowing system with availability control, and borrowed books summary via aggregation.
https://github.com/maksudulhaque2000/assignment-3-l2

backend dotenv eslint expressjs mongodb mongoose nodejs nodemon typescript

Last synced: about 2 months ago
JSON representation

A robust Library Management API built with Node.js, Express, TypeScript, and MongoDB (Mongoose). Features CRUD for books, borrowing system with availability control, and borrowed books summary via aggregation.

Awesome Lists containing this project

README

          

# 📚 Library Management API


Library Management API

A polished library management backend built with **Express.js**, **TypeScript**, and **MongoDB (Mongoose)**. The API manages books, tracks borrow transactions, enforces inventory rules, and returns consistent JSON responses for client applications or API testing tools.

## Live Project

- [Live Deployment](https://assignment-3-l2-three.vercel.app/)

## Overview

This project is a RESTful API for a basic library management system. It supports full CRUD for books, borrowing records, filtering and pagination for book listings, and a summarized borrowed-books report. The codebase uses TypeScript, Mongoose schema validation, custom error handling, and reusable response helpers to keep the API predictable and maintainable.

## Key Features

- Book CRUD operations with MongoDB persistence.
- Book listing with `genre` filtering, dynamic sorting, pagination, and result limits.
- Borrow flow that validates book IDs, checks inventory, deducts copies, and stores borrow records.
- Borrowed-books summary grouped by book with total borrowed quantity.
- Automatic `available` flag management based on `copies` count.
- Strong validation for required fields, enum values, unique ISBN, positive integer quantities, and non-negative copies.
- Consistent success and error response structure.
- Centralized error middleware for validation errors, duplicate keys, cast errors, and custom API errors.
- CORS enabled for API consumption from external clients.

## Tech Stack

- **Runtime:** Node.js
- **Framework:** Express.js 5
- **Language:** TypeScript
- **Database:** MongoDB
- **ODM:** Mongoose
- **Utilities:** dotenv, cors
- **Tooling:** nodemon, ts-node, ESLint

## Project Structure

```bash
src/
├── app.ts
├── config/
│ └── db.ts
├── controllers/
│ ├── book.controller.ts
│ └── borrow.controller.ts
├── middleware/
│ └── errorHandler.ts
├── models/
│ ├── book.model.ts
│ └── borrow.model.ts
├── routes/
│ ├── book.routes.ts
│ └── borrow.routes.ts
├── utils/
│ ├── apiError.ts
│ └── apiResponse.ts
└── types.ts
```

## API Flow

- The server starts from `src/app.ts`.
- Database connection is initialized through `src/config/db.ts`.
- Book endpoints live under `/api/books`.
- Borrow endpoints live under `/api/borrow`.
- All unhandled routes return a structured 404 response.
- Errors are normalized by the global error handler before being sent to the client.

## Environment Variables

Create a `.env` file in the project root with the following values:

```env
MONGODB_URI=your_mongodb_connection_string
PORT=3000
```

`MONGODB_URI` is required. If it is missing, the app exits during startup.

## Installation

1. Clone the repository.

```bash
git clone https://github.com/maksudulhaque2000/Assignment-3-L2.git
cd Assignment-3-L2
```

2. Install dependencies.

```bash
npm install
```

3. Configure environment variables.
```bash
MONGODB_URI=your_mongodb_connection_string
PORT=3000
```

## Available Scripts

- `npm run dev` - Start the app in development mode with `nodemon` and `ts-node`.
- `npm run build` - Compile TypeScript to JavaScript.
- `npm start` - Run the compiled production build from `dist/app.js`.
- `npm run lint` - Run ESLint across the project.
- `npm run lint:fix` - Run ESLint and automatically fix what it can.

## Running the Project

Development:

```bash
npm run dev
```

Production build:

```bash
npm run build
npm start
```

The API will be available at `http://localhost:3000` by default.

## Response Format

Successful responses use the shared response shape created by `ApiResponse`:

```json
{
"statusCode": 200,
"data": {},
"message": "Success",
"success": true
}
```

Error responses are centralized by the error handler and follow this pattern:

```json
{
"message": "Validation failed",
"success": false,
"error": {}
}
```

## Book Model

Each book document includes:

- `title`
- `author`
- `genre`
- `isbn`
- `description`
- `copies`
- `available`
- timestamps

Validation rules:

- `title`, `author`, `genre`, `isbn`, and `copies` are required.
- `genre` must be one of `FICTION`, `NON_FICTION`, `SCIENCE`, `HISTORY`, `BIOGRAPHY`, or `FANTASY`.
- `isbn` must be unique.
- `copies` must be a non-negative integer.
- `available` is updated automatically from the `copies` value.

## Borrow Model

Each borrow document includes:

- `book` reference
- `quantity`
- `dueDate`
- timestamps

Validation rules:

- `book` is required and must reference a valid book ID.
- `quantity` must be a positive integer.
- `dueDate` is required.

## API Endpoints

Base URL:

```bash
http://localhost:3000/api
```

### Root Health Message

- `GET /`
- Returns a welcome message for the API.

### Books

#### Create a Book

- `POST /books`

Request body:

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

Success response:

```json
{
"statusCode": 201,
"data": {
"title": "The Theory of Everything",
"author": "Stephen Hawking"
},
"message": "Book created successfully",
"success": true
}
```

#### Get All Books

- `GET /books`

Query options:

- `filter` - filter by genre.
- `sortBy` - sort by `title`, `author`, `genre`, `isbn`, `copies`, `createdAt`, or `updatedAt`.
- `sort` - `asc` or `desc`.
- `limit` - number of records per page.
- `page` - page number.

Example:

```bash
GET /books?filter=FANTASY&sortBy=createdAt&sort=desc&limit=5&page=1
```

The response includes pagination metadata:

```json
{
"statusCode": 200,
"data": [],
"message": "Books retrieved successfully",
"success": true,
"pagination": {
"currentPage": 1,
"itemsPerPage": 5,
"totalItems": 0,
"totalPages": 0
}
}
```

#### Get Book by ID

- `GET /books/:bookId`

#### Update Book

- `PUT /books/:bookId`

#### Delete Book

- `DELETE /books/:bookId`

### Borrowing

#### Borrow a Book

- `POST /borrow`

Request body:

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

Behavior:

- Validates the book ID.
- Checks available copies before borrowing.
- Deducts `copies` using the model static method.
- Saves a borrow record only after inventory is updated.

#### Borrowed Books Summary

- `GET /borrow`

Returns a grouped summary of borrowed books with:

- book title
- ISBN
- total borrowed quantity

## Error Handling

Common API errors are handled centrally:

- `400` for validation failures, invalid IDs, and business-rule violations.
- `404` for missing books or unknown routes.
- `409` for duplicate key conflicts such as repeated ISBN values.
- `500` for unexpected server-side issues.

## Example Success / Error Notes

- On a successful borrow request, the API stores the borrow record and decreases the corresponding book copy count.
- If a borrow request exceeds available stock, the API returns a `400` error with the message `Not enough copies available to borrow.`
- If a book ID is invalid, the API returns a `400` error before touching the database.

## Useful Notes

- CORS is enabled globally.
- The API is ready to be used from Postman, Insomnia, or any frontend client.
- The app connects to MongoDB during startup and exits if the database connection fails.

## Contact

If you want to connect or see more work, use the links below.

## Creator Links

- [Portfolio](https://maksudul-haque.vercel.app/)
- [GitHub](https://github.com/maksudulhaque2000)
- [LinkedIn](https://www.linkedin.com/in/maksudulhaque2000/)
- [Facebook](https://www.facebook.com/maksudulhaque2000)
- [YouTube](https://www.youtube.com/@maksudulhaque2000)