A robust NestJS TypeScript microservice for inventory management with MongoDB integration, featuring advanced search capabilities and comprehensive CRUD operations for products and categories.
- Product Management: Complete CRUD operations with advanced filtering
- Category Management: Hierarchical category system with soft delete
- Advanced Search: MongoDB aggregation-powered search with multiple filters
- Search Suggestions: Intelligent autocomplete for products and categories
- Low Stock Monitoring: Automatic low stock threshold tracking
- Data Validation: Comprehensive input validation with class-validator
- Error Handling: Centralized exception handling with detailed error responses
- API Documentation: Interactive Swagger/OpenAPI documentation + Postman collection
- Comprehensive Testing: 70%+ test coverage with unit, integration, and E2E tests
- Cross-Platform Support: Works seamlessly on Windows, macOS, and Linux
- Framework: NestJS (Node.js)
- Language: TypeScript
- Database: MongoDB with Mongoose ODM
- Validation: class-validator, class-transformer
- Documentation: Swagger/OpenAPI 3.0
- Testing: Jest, Supertest (Unit, Integration, E2E)
- Configuration: @nestjs/config
- API Testing: Postman collection included
- Node.js (v18 or higher)
- MongoDB (local or MongoDB Atlas)
- npm or yarn package manager
Get the API running in under 5 minutes:
-
Clone and Install
git clone <repository-url> cd inventory-api npm install
-
Setup Environment
# Create .env file echo "MONGODB_URI=mongodb://localhost:27017/inventory-api" > .env echo "DATABASE_NAME=inventory-api" >> .env echo "PORT=3000" >> .env
-
Start Development Server
npm run start:dev
-
Access Documentation
- API Docs: http://localhost:3000/api
- Test Endpoints: Import
/postman/Inventory-API.postman_collection.json
-
Run Tests
npm run test:cov
-
Clone the repository
git clone <repository-url> cd inventory-api
-
Install dependencies
npm install
-
Environment Configuration
Create a
.envfile in the root directory:# Database Configuration MONGODB_URI=mongodb://localhost:27017/inventory-api DATABASE_NAME=inventory-api # Application Configuration PORT=3000 NODE_ENV=development
-
Start MongoDB
Make sure MongoDB is running on your system or configure MongoDB Atlas connection.
npm run start:devnpm run build
npm run start:prodnpm run start:debugThe API will be available at http://localhost:3000
This project includes cross-platform scripts that work on Windows, macOS, and Linux:
# Development
npm run start:dev # Start in development mode with hot reload
npm run start:debug # Start in debug mode with debugging enabled
npm run build # Build the application for production
npm run start:prod # Start the built application in production mode
# Testing
npm test # Run unit and integration tests
npm run test:watch # Run tests in watch mode
npm run test:cov # Run tests with coverage report
npm run test:e2e # Run end-to-end tests
# Code Quality
npm run lint # Run ESLint to check code quality
npm run format # Format code with Prettier (if configured)Once the application is running, access the interactive API documentation at:
The Swagger interface provides:
- Complete API endpoint documentation
- Interactive request/response examples
- Schema definitions for all DTOs
- Try-it-out functionality for testing endpoints
- Authentication examples (if applicable)
You can also use the Postman collection located at /postman/Inventory-API.postman_collection.json for comprehensive API testing.
| Method | Endpoint | Description |
|---|---|---|
| GET | /categories |
Get all categories with pagination |
| GET | /categories/:id |
Get category by ID |
| GET | /categories/slug/:slug |
Get category by slug |
| POST | /categories |
Create new category |
| PATCH | /categories/:id |
Update category |
| DELETE | /categories/:id |
Soft delete category |
| DELETE | /categories/:id/hard |
Permanently delete category |
| GET | /categories/search/suggestions |
Get category search suggestions |
| Method | Endpoint | Description |
|---|---|---|
| GET | /products |
Get all products with pagination |
| GET | /products/:id |
Get product by ID |
| GET | /products/sku/:sku |
Get product by SKU |
| GET | /products/category/:categoryId |
Get products by category |
| GET | /products/low-stock |
Get low stock products |
| POST | /products |
Create new product |
| PATCH | /products/:id |
Update product |
| PATCH | /products/:id/stock |
Update product stock |
| DELETE | /products/:id |
Soft delete product |
| DELETE | /products/:id/hard |
Permanently delete product |
| Method | Endpoint | Description |
|---|---|---|
| GET | /products/search |
Advanced product search |
| GET | /products/search/suggestions |
Get search suggestions |
| GET | /products/search/filters |
Get available search filters |
- q: General text search across name, description, brand, SKU, and tags
- name: Search by product name
- brand: Filter by brand
- categoryId: Filter by category
- minPrice/maxPrice: Price range filter
- minQuantity/maxQuantity: Stock quantity filter
- tags: Filter by tags (comma-separated)
- isActive: Filter by active status
- isFeatured: Filter by featured status
- isLowStock: Filter by low stock status
- specifications: Search within product specifications
- sortBy: Sort by relevance, price, name, createdAt, quantity
- order: Sort order (asc/desc)
- page/limit: Pagination parameters
# General text search
GET /products/search?q=macbook&page=1&limit=5
# Price range filter
GET /products/search?minPrice=500&maxPrice=2000&sortBy=price&order=asc
# Brand and category filter
GET /products/search?brand=Apple&categoryId=60f7b3b3b3f3f3f3f3f3f3f3
# Tags filter
GET /products/search?tags=laptop,professional&sortBy=name{
name: string; // Required, 2-200 chars
description: string; // Required, 10-1000 chars
price: number; // Required, min 0, max 999999.99
sku: string; // Required, unique, auto-uppercase
quantity: number; // Required, min 0
lowStockThreshold: number; // Default: 5
categoryId: ObjectId; // Required, references Category
brand?: string; // Optional, max 100 chars
tags: string[]; // Array of tags
images: string[]; // Array of image URLs
specifications: object; // Flexible JSON object
isActive: boolean; // Default: true
isFeatured: boolean; // Default: false
createdAt: Date; // Auto-generated
updatedAt: Date; // Auto-generated
}{
name: string; // Required, unique, 2-100 chars
description: string; // Required, 10-500 chars
slug: string; // Auto-generated from name
isActive: boolean; // Default: true
createdAt: Date; // Auto-generated
updatedAt: Date; // Auto-generated
}This project maintains 70%+ test coverage with comprehensive test suites:
# Run all tests
npm test
# Run tests with coverage report
npm run test:cov
# Run tests in watch mode
npm run test:watch
# Run end-to-end tests
npm run test:e2e- Unit Tests: Individual service and utility function testing
- Controller Tests: HTTP endpoint testing with mocked dependencies
- Integration Tests: Database integration and service interaction testing
- E2E Tests: Full application workflow testing
Current test coverage includes:
- Controllers: 100% coverage for all endpoints
- Services: Comprehensive business logic testing
- Error Handling: Exception filters and validation testing
- Search Functionality: Advanced search and aggregation testing
- Import the Postman collection from
/postman/Inventory-API.postman_collection.json - The collection includes:
- All API endpoints
- Environment variables
- Automated tests
- Workflow examples
- Category Management: CRUD operations and search
- Product Management: CRUD operations with validation
- Advanced Search: All search variations and filters
- Error Handling: Invalid data and edge cases
src/
βββ categories/
β βββ dto/ # Data Transfer Objects
β βββ schemas/ # MongoDB schemas
β βββ categories.controller.ts
β βββ categories.service.ts
β βββ categories.module.ts
β βββ categories.controller.spec.ts # Controller tests
βββ products/
β βββ dto/
β βββ schemas/
β βββ services/
β β βββ search.service.ts # Advanced search logic
β β βββ search.service.spec.ts # Search service tests
β βββ products.controller.ts
β βββ products.service.ts
β βββ products.module.ts
β βββ products.controller.spec.ts # Controller tests
β βββ products.service.spec.ts # Service tests
βββ common/
β βββ dto/ # Common DTOs
β βββ filters/ # Exception filters
β β βββ all-exceptions.filter.ts
β β βββ all-exceptions.filter.spec.ts # Filter tests
β βββ interfaces/ # Base interfaces
β βββ pipes/ # Validation pipes
βββ config/
β βββ database.config.ts # Database configuration
βββ database/
β βββ seeds/ # Database seeding
βββ app.controller.ts
βββ app.service.ts
βββ app.module.ts
βββ app.controller.spec.ts # App controller tests
βββ main.ts # Application entry point
test/
βββ app.e2e-spec.ts # End-to-end tests
βββ jest-e2e.json # E2E test configuration
postman/
βββ Inventory-API.postman_collection.json # API collection
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "run", "start:prod"]NODE_ENV=production
PORT=3000
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/inventory-api
DATABASE_NAME=inventory-api- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
main: Production-ready codedev: Development integration branchfeature/*: Feature development branches
- Use TypeScript interfaces and DTOs for type safety
- Follow NestJS best practices with modules, controllers, and services
- Implement proper error handling and validation
- Use MongoDB schemas with Mongoose ODM
- Follow RESTful API conventions
- Implement proper logging and monitoring
- Write comprehensive tests for new features
- Maintain Swagger documentation for API changes
- Use environment variables for configuration
- Write descriptive commit messages
-
MongoDB Connection Failed
- Verify MongoDB is running
- Check connection string in
.env - Ensure database permissions
-
Validation Errors
- Check request body format against Swagger documentation
- Verify required fields are provided
- Review data type constraints in DTOs
-
Search Returns Empty Results
- Verify products have
isActive: true - Check category associations
- Review search parameters in Swagger docs
- Verify products have
-
Tests Failing
- Run
npm testto see detailed error messages - Check if MongoDB test database is accessible
- Verify all dependencies are installed with
npm install
- Run
-
Swagger Documentation Not Loading
- Ensure application is running on correct port
- Check that
/apiendpoint is accessible - Verify Swagger setup in
main.ts
This project is licensed under the MIT License.
Ezequiel Sanchez
- NestJS team for the amazing framework and comprehensive documentation
- MongoDB team for the powerful database and aggregation framework
- Jest community for the excellent testing framework
- Swagger/OpenAPI for standardized API documentation
- The open source community for continuous inspiration
- Alondra, my wife, for enduring my coding marathons and providing endless support
For more information or support, please open an issue in the repository.