A modern, full-featured e-book store API built with NestJS - From browsing to payment, powered by AI
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.
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.
- 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).
- π€ 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
.docxand.pdfformats 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.
π Read the full story here: THE_PROCESS.md
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)
- Clone repository
git clone https://github.com/Hieuej147/ebook-api-.git
cd API-EBook- Install dependencies
npm install- 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- Setup database with Docker (recommended)
# Start PostgreSQL container
npm run db:test:up
# Or use docker-compose
docker-compose up -d- Run Prisma migrations
npx prisma migrate dev- Seed database (optional)
npx prisma db seed- Start development server
npm run start:devServer running at: http://localhost:3000
API Documentation: http://localhost:3000/api/docs
# 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 PrettierAPI-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
POST /auth/signup- User registrationPOST /auth/signin- User loginPOST /auth/refresh- Refresh access tokenPOST /auth/logout- User logout
GET /users/me- Get current user profilePATCH /users/me- Update profile informationPATCH /users/me/password- Change account passwordDELETE /users/me- Delete account
GET /books- List all books (Public)GET /books/:id- Get book detailsPOST /books- Create a new book (Admin Only)PATCH /books/:id- Update book details (Admin Only)DELETE /books/:id- Remove a book (Admin Only)
GET /cart- View current shopping cartPOST /cart/items- Add item to cartPATCH /cart/items/:id- Update item quantityDELETE /cart/items/:id- Remove item from cart
POST /orders- Create a new order from cartGET /orders- View personal order historyGET /orders/:id- Get specific order detailsPATCH /orders/:id- Update order informationDELETE /orders/:id- Cancel an order
POST /payments/create-intent- Initialize Stripe Payment IntentPOST /payments/confirm- Confirm successful payment status
Explore the full API documentation via Swagger at: http://localhost:3000/api/docs
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
Contributions, issues, and feature requests are welcome!
- Fork the project
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is UNLICENSED - it's for educational and portfolio purposes.
Hieu Dev
- GitHub: @Hieuej147
- Email: [email protected]
- NestJS Team - For the amazing framework
- Prisma Team - For the best ORM experience
- Stripe - For comprehensive payment API
- LangChain/LangGraph - For AI agent capabilities