This is a simple backend service that:
- Fetches books containing the word “green” in their title from the Open Library API every 5 minutes
- Stores the books in a MongoDB database while preventing duplicates.
- Provides API endpoints to rent and return books.
- Ensures concurrency control so multiple users cannot rent the same book simultaneously.
- Backend: Node.js, Express.js
- Database: MongoDB with Mongoose ORM
- Scheduling: node-cron
- External API: Open Library API
- Testing: Jest, Supertest
git clone https://github.com/yourusername/book-rental-api.git
cd book-rental-apinpm installCreate a .env file and add:
MONGO_URI=your_mongodb_connection_string
PORT=5000
npm run devnpm starthttps://documenter.getpostman.com/view/29626287/2sAYkKJxjC
Returns the list of books stored in the database.
[
{
"_id": "65b6f0cf8c6a1b001e8b8a4a",
"title": "Green Eggs and Ham",
"author": "Dr. Seuss",
"openLibraryId": "OL12345M",
"isRented": false
}
]Rents a book if it’s not already rented.
{
"bookId": "65b6f0cf8c6a1b001e8b8a4a",
"userId": "user123"
}{
"message": "Book rented successfully",
"book": {
"_id": "65b6f0cf8c6a1b001e8b8a4a",
"title": "Green Eggs and Ham",
"isRented": true,
"rentedBy": "user123"
}
}{
"error": "Book is already rented by another user"
}Returns a book if it was previously rented by the user.
{
"bookId": "65b6f0cf8c6a1b001e8b8a4a",
"userId": "user123"
}{
"message": "Book returned successfully",
"book": {
"_id": "65b6f0cf8c6a1b001e8b8a4a",
"title": "Green Eggs and Ham",
"isRented": false
}
}{
"error": "Book was not rented by this user"
}- A cron job runs every 5 minutes (or 10 seconds in test mode) to fetch books containing "green" in the title.
- The fetched books are upserted into MongoDB to avoid duplicates.
To change the interval to 10 seconds, modify scheduler.js:
cron.schedule('*/10 * * * * *', async () => {
console.log('Fetching books from Open Library...');
await fetchAndStoreBooks();
});For production, revert it to every 5 minutes:
cron.schedule('*/5 * * * *', async () => {
console.log('Fetching books from Open Library...');
await fetchAndStoreBooks();
});/book-rental-api
│── /models
│ ├── Book.js # Mongoose model for books
│── /routes
│ ├── bookRoutes.js # API routes for book rental system
│── /services
│ ├── bookService.js # Service for fetching books from Open Library
│── /utils
│ ├── scheduler.js # Cron job for fetching books every 5 min
│── server.js # Main entry point
│── package.json # Dependencies and scripts
│── README.md # API Documentation
- User Authentication: Implement JWT-based authentication.
- Book Reviews API: Allow users to add ratings/reviews for books.
- Pagination & Filtering: Enhance
/booksendpoint to support pagination.