Skip to content

Hieuej147/ebook-api

Repository files navigation

πŸ“š API-EBook

A modern, full-featured e-book store API built with NestJS - From browsing to payment, powered by AI

✨ Introduction

API-EBook is a comprehensive backend system for an electronic bookstore, engineered with NestJS 11.x and TypeScript. This project is not just a simple APIβ€”it is a production-ready backend architecture featuring robust authentication, role-based access control (RBAC), complex inventory management, integrated payment processing, document generation, and a cutting-edge AI Agent integration.

Why build this project?

To truly master a framework, one must build a functional, real-world application. API-EBook was created with these core objectives:

  • 🎯 Best Practices: Implementing modular architecture, dependency injection, custom decorators, guards, and interceptors.
  • πŸ” Security-First: Building a complete Auth/Authz system with JWT (Access/Refresh tokens) and role-based permissions.
  • πŸ’³ Financial Integration: Integrating Stripe for real-world payment processing.
  • πŸ€– AI Innovation: Leveraging CopilotKit and LangGraph to create an intelligent AI assistant.
  • πŸ“Š Scalable Design: Architecting a complex database schema using Prisma ORM and PostgreSQL.

πŸ› οΈ Tech Stack

πŸ“¦ Technologies

  • Core Framework: NestJS 11.x, TypeScript.
  • Database & ORM: PostgreSQL, Prisma ORM 7.x, Redis (Caching & Rate Limiting).
  • Security: Passport JWT, Argon2 (Password Hashing), Custom RBAC Guards.
  • Payment & Cloud: Stripe (Payment Intent API), Cloudinary (Image Hosting).
  • AI Integration: LangGraph (Workflows), CopilotKit Runtime, OpenAI (LLM).
  • Document Generation: Docx (Word), PDFKit (PDF), Markdown-it (Parsing).
  • Testing: Jest (Unit/Integration), Pactum (E2E API Testing).

πŸ¦„ Features

  • πŸ‘€ User Management: Signup/Signin with JWT strategy, automated token refresh, and profile management for Normal/Premium users.
  • πŸ“– Content System: Full CRUD for books and categories, featuring Markdown support for chapters and Cloudinary integration for covers.
  • πŸ›’ Intelligent Cart: Stock-aware shopping cart with the ability to merge guest carts to user accounts upon login.
  • πŸ“¦ Order Lifecycle: Complete order tracking (Pending β†’ Processing β†’ Shipped β†’ Delivered) with automatic stock deduction and restoration on cancellation.
  • πŸ’³ Secure Checkout: End-to-end payment flow via Stripe with transaction history tracking.
  • πŸ“„ Document Export: High-quality export of book content to .docx and .pdf formats with professional formatting.
  • πŸ€– AI Agent Assistant: An integrated assistant for book lookups, web-based content extraction (Tavily), and shop analytics.
  • πŸ›‘οΈ Security & Performance: Custom Throttler for rate limiting, class-validator for input validation, and API Key protection for internal endpoints.

πŸ”„ The Process & πŸ’‘ What I Learned

πŸ‘‰ Read the full story here: THE_PROCESS.md


πŸš€ Getting Started

Prerequisites

Ensure you have the following installed:

  • Node.js (Version >= 18.x)
  • npm or yarn
  • PostgreSQL (Version >= 14.x)
  • Redis (Optional, required for caching/throttling features)
  • Docker & Docker Compose (Recommended for easy database setup)

Installation

  1. Clone repository
git clone https://github.com/Hieuej147/ebook-api-.git
cd API-EBook
  1. Install dependencies
npm install
  1. Setup environment variables

Create a .env file in the root:

# Database
DATABASE_URL="postgresql://username:password@localhost:5432/ebook_db?schema=public"

# JWT Secrets
JWT_SECRET="your-super-secret-jwt-key"
JWT_REFRESH_SECRET="your-super-secret-refresh-key"

# Stripe
STRIPE_SECRET_KEY="sk_test_your_stripe_secret_key"

# Cloudinary
CLOUDINARY_NAME="your-cloudinary-cloud-name"
CLOUDINARY_API_KEY="your-cloudinary-api-key"
CLOUDINARY_API_SECRET="your-cloudinary-api-secret"

# CORS
ALLOWED_ORIGINS="http://localhost:3000,http://localhost:5173"

# Port
PORT=3000

# AI Agent (optional)
NESTJS_AGENT_URL="http://localhost:8123"
OPENAI_API_KEY="your-openai-apt-key"
TAVILY_API_KEY="your-tavyly-api-key"

# Redis (optional)
REDIS_HOST="localhost"
REDIS_PORT=6379
  1. Setup database with Docker (recommended)
# Start PostgreSQL container
npm run db:test:up

# Or use docker-compose
docker-compose up -d
  1. Run Prisma migrations
npx prisma migrate dev
  1. Seed database (optional)
npx prisma db seed
  1. Start development server
npm run start:dev

Server running at: http://localhost:3000

API Documentation: http://localhost:3000/api/docs


πŸ“– Available Scripts

# Development
npm run start          # Start app
npm run start:dev      # Start with watch mode
npm run start:debug    # Start with debug mode

# Build
npm run build          # Build for production
npm run start:prod     # Start production build

# Database
npm run db:test:up     # Start PostgreSQL container
npm run db:test:rm     # Remove PostgreSQL container
npm run db:test:restart # Restart database with fresh migrations
npm run db:test:studio # Open Prisma Studio

# Testing
npm run test           # Run unit tests
npm run test:watch     # Run tests in watch mode
npm run test:cov       # Run tests with coverage
npm run test:e2e       # Run E2E tests

# Code Quality
npm run lint           # Lint and fix
npm run format         # Format code with Prettier

πŸ—‚οΈ Project Structure

API-EBook/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.ts                    # Application entry point
β”‚   β”œβ”€β”€ app.module.ts              # Root module
β”‚   β”œβ”€β”€ common/                    # Shared utilities
β”‚   β”‚   β”œβ”€β”€ decorators/           # Custom decorators
β”‚   β”‚   β”œβ”€β”€ guards/               # Auth guards
β”‚   β”‚   └── interfaces/           # TypeScript interfaces
β”‚   └── module/                    # Feature modules
β”‚       β”œβ”€β”€ auth/                 # Authentication
β”‚       β”œβ”€β”€ user/                 # User management
β”‚       β”œβ”€β”€ books/                # Books CRUD
β”‚       β”œβ”€β”€ category/             # Categories
β”‚       β”œβ”€β”€ chapters/             # Book chapters
β”‚       β”œβ”€β”€ cart/                 # Shopping cart
β”‚       β”œβ”€β”€ orders/               # Order management
β”‚       β”œβ”€β”€ payments/             # Stripe integration
β”‚       β”œβ”€β”€ export-doc/           # Document export
β”‚       β”œβ”€β”€ stats/                # Statistics
β”‚       β”œβ”€β”€ copilotkit/           # AI agent
β”‚       β”œβ”€β”€ internal-api/         # Internal APIs
β”‚       β”œβ”€β”€ cloudinary/           # Image upload
β”‚       └── prisma/               # Prisma service
β”œβ”€β”€ prisma/
β”‚   β”œβ”€β”€ schema.prisma             # Database schema
β”‚   └── migrations/               # Migration history
β”œβ”€β”€ test/                          # E2E tests
β”œβ”€β”€ ai-agent-python/              # Python AI agent
└── docker-compose.yml            # Docker configuration

πŸ“Š API Endpoints Overview

πŸ” Authentication

  • POST /auth/signup - User registration
  • POST /auth/signin - User login
  • POST /auth/refresh - Refresh access token
  • POST /auth/logout - User logout

πŸ‘€ Users

  • GET /users/me - Get current user profile
  • PATCH /users/me - Update profile information
  • PATCH /users/me/password - Change account password
  • DELETE /users/me - Delete account

πŸ“– Books

  • GET /books - List all books (Public)
  • GET /books/:id - Get book details
  • POST /books - Create a new book (Admin Only)
  • PATCH /books/:id - Update book details (Admin Only)
  • DELETE /books/:id - Remove a book (Admin Only)

πŸ›’ Shopping Cart

  • GET /cart - View current shopping cart
  • POST /cart/items - Add item to cart
  • PATCH /cart/items/:id - Update item quantity
  • DELETE /cart/items/:id - Remove item from cart

πŸ“¦ Orders

  • POST /orders - Create a new order from cart
  • GET /orders - View personal order history
  • GET /orders/:id - Get specific order details
  • PATCH /orders/:id - Update order information
  • DELETE /orders/:id - Cancel an order

πŸ’³ Payments

  • POST /payments/create-intent - Initialize Stripe Payment Intent
  • POST /payments/confirm - Confirm successful payment status

Explore the full API documentation via Swagger at: http://localhost:3000/api/docs


πŸ” Authentication Flow

1. User β†’ POST /auth/signup β†’ Server
   └─> Returns: { user, accessToken, refreshToken }

2. User β†’ POST /auth/signin β†’ Server
   └─> Returns: { user, accessToken, refreshToken }

3. User β†’ Request with Authorization: Bearer <accessToken>
   └─> Grants access to protected routes

4. When accessToken expires:
   User β†’ POST /auth/refresh with refreshToken
   └─> Returns: { new accessToken, new refreshToken }

5. User β†’ POST /auth/logout
   └─> Server invalidates current refreshToken
Loading

🀝 Contributing

Contributions, issues, and feature requests are welcome!

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

πŸ“ License

This project is UNLICENSED - it's for educational and portfolio purposes.


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

Hieu Dev


πŸ™ Acknowledgments

  • NestJS Team - For the amazing framework
  • Prisma Team - For the best ORM experience
  • Stripe - For comprehensive payment API
  • LangChain/LangGraph - For AI agent capabilities

Built with ❀️ using NestJS and TypeScript

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors