A comprehensive, production-ready backend system for managing food-related data built with NestJS, Prisma, and PostgreSQL. The system provides secure API endpoints, OpenFoodFacts integration, user authentication via Keycloak, and is fully containerized for consistent deployment across environments.
- Modern Architecture: Built with NestJS, TypeScript, and Prisma ORM
- Food Data Management: Complete CRUD operations for food items
- OpenFoodFacts Integration: Automatic nutritional data retrieval from external API
- User Management: User profiles, preferences, and dietary restrictions
- Authentication & Authorization: Keycloak integration with JWT tokens and role-based access control
- Caching: Redis-based caching for improved performance
- API Documentation: Comprehensive OpenAPI/Swagger documentation
- Testing: Unit, integration, and end-to-end tests with high coverage
- Monitoring: Health checks, metrics, and structured logging
- Security: Input validation, rate limiting, and security headers
- DevOps Ready: Docker containerization, Kubernetes manifests, and CI/CD pipelines
- Prerequisites
- Quick Start
- Development Setup
- API Documentation
- Testing
- Deployment
- Architecture
- Contributing
- Node.js 18+
- Docker and Docker Compose
- npm or yarn
- Git
git clone <repository-url>
cd foodmission-data-framework
npm install
Create environment files:
cp .env.example .env
cp .env.test.example .env.test
Configure your .env
file:
# Database
DATABASE_URL="postgresql://postgres:password@localhost:5432/foodmission_db?schema=public"
DATABASE_URL_TEST="postgresql://postgres:password@localhost:5432/foodmission_test_db?schema=public"
# Redis
REDIS_URL="redis://localhost:6379"
# Keycloak
KEYCLOAK_BASE_URL="http://localhost:8080"
KEYCLOAK_REALM="foodmission"
KEYCLOAK_CLIENT_ID="foodmission-api"
# OpenFoodFacts
OPENFOODFACTS_API_URL="https://world.openfoodfacts.org"
# Application
NODE_ENV="development"
PORT=3000
JWT_SECRET="your-jwt-secret-key"
# Start database and Redis services
npm run docker:up
# Generate Prisma client
npm run db:generate
# Run database migrations
npm run db:migrate:deploy
# Seed the database with initial data
npm run db:seed
# Development mode with hot reload
npm run start:dev
# The API will be available at http://localhost:3000
# Swagger documentation at http://localhost:3000/api/docs
For the best development experience, use the provided DevContainer:
- Open the project in VSCode
- Install the "Dev Containers" extension
- Press
Ctrl+Shift+P
and select "Dev Containers: Reopen in Container" - The container will automatically set up the development environment
# Install dependencies
npm install
# Set up development environment
npm run dev:setup
# Start development services
npm run docker:up
# Run database setup
npm run db:generate
npm run db:migrate:deploy
npm run db:seed:dev
# Start the application
npm run start:dev
npm run start:dev
- Start in development mode with hot reloadnpm run start:debug
- Start in debug modenpm run dev:setup
- Set up development environmentnpm run dev:reset
- Reset development database
npm run db:generate
- Generate Prisma clientnpm run db:migrate
- Create and apply new migrationnpm run db:migrate:deploy
- Apply existing migrationsnpm run db:migrate:reset
- Reset database and apply all migrationsnpm run db:studio
- Open Prisma Studio (database GUI)npm run db:seed
- Seed database with initial datanpm run db:backup
- Create database backupnpm run db:restore
- Restore database from backup
npm run test
- Run unit testsnpm run test:unit
- Run unit tests onlynpm run test:integration
- Run integration testsnpm run test:e2e
- Run end-to-end testsnpm run test:cov
- Run tests with coverage reportnpm run ci:test
- Run all tests in CI mode
npm run build
- Build the applicationnpm run start:prod
- Start in production modenpm run docker:up
- Start Docker servicesnpm run docker:down
- Stop Docker services
npm run lint
- Run ESLintnpm run format
- Format code with Prettier
The API documentation is automatically generated and available at:
- Development: http://localhost:3000/api/docs
- Production: https://your-domain.com/api/docs
POST /api/v1/auth/login
- User loginPOST /api/v1/auth/logout
- User logoutGET /api/v1/auth/profile
- Get user profile
GET /api/v1/foods
- List foods with pagination and filteringPOST /api/v1/foods
- Create new food itemGET /api/v1/foods/:id
- Get food by IDPUT /api/v1/foods/:id
- Update food itemDELETE /api/v1/foods/:id
- Delete food itemGET /api/v1/foods/barcode/:barcode
- Get food by barcodePOST /api/v1/foods/import/openfoodfacts
- Import from OpenFoodFacts
GET /api/v1/users/profile
- Get user profilePUT /api/v1/users/profile
- Update user profileGET /api/v1/users/preferences
- Get user preferencesPUT /api/v1/users/preferences
- Update user preferences
GET /api/v1/health
- Health checkGET /api/v1/health/readiness
- Readiness probeGET /api/v1/health/liveness
- Liveness probeGET /api/v1/metrics
- Prometheus metrics
curl -X POST http://localhost:3000/api/v1/foods \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"name": "Organic Banana",
"description": "Fresh organic banana",
"barcode": "1234567890123"
}'
curl "http://localhost:3000/api/v1/foods?search=banana&page=1&limit=10" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
curl -X POST http://localhost:3000/api/v1/foods/import/openfoodfacts \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"barcode": "3017620422003"
}'
The project includes comprehensive testing at multiple levels:
- Unit Tests: Test individual components in isolation
- Integration Tests: Test module interactions and database operations
- End-to-End Tests: Test complete API workflows
# Run all tests
npm test
# Run specific test types
npm run test:unit
npm run test:integration
npm run test:e2e
# Run tests with coverage
npm run test:cov
# Run tests in watch mode
npm run test:watch
# Run tests in CI mode
npm run ci:test
The project maintains high test coverage:
- Unit Tests: 85%+ coverage
- Integration Tests: Critical paths covered
- E2E Tests: Main user workflows covered
Tests are located in:
src/**/*.spec.ts
- Unit teststest/**/*.integration.spec.ts
- Integration teststest/**/*.e2e-spec.ts
- End-to-end tests
# Build the Docker image
docker build -t foodmission-data-framework .
# Run with Docker Compose
docker-compose up -d
# Development
docker-compose -f docker-compose.dev.yml up -d
# Production
docker-compose -f docker-compose.prod.yml up -d
The project includes Kubernetes manifests in the k8s/
directory:
# Deploy to Kubernetes
kubectl apply -f k8s/
# Or use the deployment script
./k8s/deploy.sh
- Deployment: Application pods with auto-scaling
- Service: Load balancer for the application
- ConfigMap: Environment configuration
- Secret: Sensitive configuration data
- Ingress: External access configuration
- HPA: Horizontal Pod Autoscaler
The project uses GitHub Actions for automated CI/CD:
- Continuous Integration: Automated testing, linting, and security scanning
- Continuous Deployment: Automated deployment to staging and production
- Quality Gates: Code coverage and security requirements
- Code Quality: ESLint, Prettier, TypeScript compilation
- Security: Dependency scanning, SAST analysis
- Testing: Unit, integration, and e2e tests
- Build: Docker image creation and registry push
- Deploy: Automated deployment to environments
- Local database and Redis
- Hot reloading enabled
- Debug logging
- Mock external services
- Shared database instance
- Production-like configuration
- Integration with external services
- Performance monitoring
- High-availability database cluster
- Redis cluster for caching
- Full monitoring and alerting
- Security hardening
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Client Apps β β Load Balancer β β API Gateway β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β β
βββββββββββββββββββββββββΌββββββββββββββββββββββββ
β
βββββββββββββββββββββββββΌββββββββββββββββββββββββ
β NestJS Application β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β Controllers Layer β β
β βββββββββββββββββββββββββββββββββββββββββββ β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β Services Layer β β
β βββββββββββββββββββββββββββββββββββββββββββ β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β Repository Layer β β
β βββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββΌβββββββββββββββββββββββ
β β β
βββββΌβββββ ββββββββΌβββββββ ββββββββΌβββββββ
βPostgreSQLβ β Redis β β Keycloak β
βDatabase β β Cache β β Auth β
ββββββββββββ βββββββββββββββ βββββββββββββββ
src/
βββ auth/ # Authentication & authorization
βββ cache/ # Caching services and decorators
βββ common/ # Shared utilities and exceptions
βββ database/ # Database configuration and services
βββ food/ # Food management module
βββ health/ # Health checks and monitoring
βββ monitoring/ # Metrics and performance monitoring
βββ security/ # Security services and middleware
βββ user/ # User management module
- Repository Pattern: Data access abstraction
- Dependency Injection: Loose coupling and testability
- Decorator Pattern: Cross-cutting concerns (caching, validation)
- Strategy Pattern: Multiple authentication strategies
- Observer Pattern: Event-driven architecture
-- Core entities
Food (id, name, description, barcode, openFoodFactsId, createdBy)
User (id, keycloakId, email, firstName, lastName)
UserPreferences (id, userId, dietaryRestrictions, allergies, preferredCategories)
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature
- Make your changes and add tests
- Run the test suite:
npm test
- Commit your changes:
git commit -m 'Add amazing feature'
- Push to the branch:
git push origin feature/amazing-feature
- Open a Pull Request
- TypeScript: Strict mode enabled
- ESLint: Airbnb configuration with custom rules
- Prettier: Consistent code formatting
- Conventional Commits: Standardized commit messages
- Test Coverage: Minimum 80% coverage required
This project is licensed under the AGPL-3.0 License - see the LICENSE file for details.
- Documentation: Full documentation
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- NestJS - Progressive Node.js framework
- Prisma - Next-generation ORM
- OpenFoodFacts - Open food database
- Keycloak - Identity and access management