A comprehensive NestJS-based REST API designed specifically for creating and managing Material-UI themes. Theme Factory provides a complete backend solution for theme management systems with robust user authentication, advanced theme configuration, and comprehensive CRUD operations.
Theme Factory is a specialized API that allows developers and designers to:
- Create, store, and manage Material-UI theme configurations
- Validate theme structures against MUI specifications
- Support Google Fonts integration for custom typography
- Provide comprehensive theme categorization with tags
- Maintain audit trails for theme creation and updates
- Export themes for use in React/MUI applications
- User registration and authentication system
- Secure password hashing with bcrypt
- JWT-based session management
- User profile management with audit trails
- Material-UI Compatibility: Full support for MUI theme structure
- Rich Configuration: Palette, typography, spacing, shadows, breakpoints
- Typography Variants: Complete support for all MUI typography variants (h1-h6, body1/2, button, caption, overline)
- Google Fonts Integration: Load and configure custom fonts from Google Fonts
- Component Overrides: Support for MUI component customization
- Theme Validation: Comprehensive validation using class-validator
- JSONB Storage: Flexible theme configuration storage in PostgreSQL
- Advanced Filtering: Search by name, creator, tags, and more
- Pagination: Efficient data retrieval with customizable page sizes
- Sorting: Multiple sorting options (date, name, popularity)
- Tagging System: Categorize themes with multiple tags
- Preview Images: Optional theme preview image support
- Active/Inactive States: Control theme visibility and availability
- JWT Authentication: Secure API access with Bearer tokens
- Input Validation: Comprehensive validation with class-validator
- Type Safety: Full TypeScript support throughout the application
- CORS Configuration: Proper cross-origin resource sharing setup
- Error Handling: Consistent error responses and logging
- Swagger/OpenAPI: Interactive API documentation with examples
- Comprehensive Testing: Unit and E2E tests with Jest
- Code Quality: ESLint and Prettier configuration
- Database Migrations: TypeORM synchronization and schema management
- NestJS - Progressive Node.js framework with TypeScript support
- Express.js - Underlying HTTP server platform
- PostgreSQL 14.3 - Robust relational database with JSONB support
- TypeORM - Advanced ORM with TypeScript support
- Docker Compose - Containerized database setup
- JWT (JSON Web Tokens) - Stateless authentication
- Passport.js - Authentication middleware
- bcrypt - Password hashing and security
- class-validator - Decorator-based validation
- class-transformer - Object transformation and serialization
- Swagger/OpenAPI 3.0 - Interactive API documentation
- Nest Swagger - Automatic documentation generation
- TypeScript 5.7 - Static type checking and modern JavaScript features
- Jest - Testing framework for unit and E2E tests
- ESLint + Prettier - Code quality and formatting
- Supertest - HTTP assertion testing
- Docker - Containerization support
- Node.js 18+ - Runtime environment
theme-factory/
βββ src/
β βββ auth/ # π Authentication Module
β β βββ auth.controller.ts # Login/register endpoints
β β βββ auth.service.ts # Authentication business logic
β β βββ auth.module.ts # Module configuration
β β βββ decorators/ # Custom decorators (GetUser)
β β βββ strategies/ # JWT Passport strategy
β β
β βββ users/ # π₯ User Management Module
β β βββ dto/ # Data Transfer Objects
β β β βββ create-user.dto.ts
β β β βββ login-user.dto.ts
β β β βββ update-user.dto.ts
β β βββ entities/ # Database entities
β β β βββ user.entity.ts # User database model
β β βββ users.controller.ts # User CRUD endpoints
β β βββ users.service.ts # User business logic
β β βββ users.module.ts # Module configuration
β β
β βββ themes/ # π¨ Theme Management Module
β β βββ dto/ # Theme Data Transfer Objects
β β β βββ create-theme.dto.ts # Comprehensive MUI theme validation
β β β βββ theme-query.dto.ts # Search and filtering options
β β β βββ update-theme.dto.ts # Theme update validation
β β βββ entities/
β β β βββ theme.entity.ts # Theme database model with JSONB
β β βββ themes.controller.ts # Theme CRUD endpoints
β β βββ themes.service.ts # Theme business logic
β β βββ themes.module.ts # Module configuration
β β
β βββ common/ # π§ Shared Utilities
β β βββ dto/
β β β βββ pagination.dto.ts # Pagination utilities
β β βββ common.module.ts # Shared module configuration
β β
β βββ types/ # π TypeScript Definitions
β β βββ auth-response.ts # Authentication response types
β β βββ index.ts # Type exports
β β
β βββ config/ # βοΈ Configuration Files
β βββ app.module.ts # Root application module
β βββ main.ts # Application bootstrap
β
βββ test/ # π§ͺ Test Files
β βββ app.e2e-spec.ts # End-to-end tests
β βββ jest-e2e.json # E2E test configuration
β
βββ docker-compose.yml # π³ Database containerization
βββ .env.template # Environment variables template
βββ package.json # Dependencies and scripts
βββ tsconfig.json # TypeScript configuration
βββ eslint.config.mjs # ESLint configuration
βββ README.md # Project documentation
Before running Theme Factory, ensure you have the following installed:
- Node.js (version 18 or higher) - Download
- npm or yarn - Package manager (npm comes with Node.js)
- PostgreSQL (version 14+) - Download
- Docker & Docker Compose - For easy database setup
- Git - For version control
- VS Code - Recommended IDE with TypeScript support
git clone <repository-url>
cd theme-factory# Using npm
npm install
# Or using yarn
yarn install# Copy the environment template
cp .env.template .envConfigure your .env file with the following variables:
# Database Configuration
POSTGRES_PASSWORD=your_secure_password
POSTGRES_DB=theme_factory_db
POSTGRES_CONTAINER_NAME=theme_factory_postgres
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
# Application Configuration
PORT=3000
HOST_API=http://localhost:3000
NODE_ENV=development
# JWT Configuration
JWT_SECRET=your_jwt_secret_key_here
JWT_EXPIRES_IN=7d# Start PostgreSQL container
docker-compose up -d
# Verify database is running
docker ps- Install PostgreSQL on your system
- Create a database named
theme_factory_db - Update the
.envfile with your local database credentials
# The application will automatically sync the database schema on first run
npm run start:dev# Development mode with hot reload
npm run start:dev
# Development mode with debugging
npm run start:debug
# Production mode
npm run start:prod
# Build the application
npm run build- Start the database:
docker-compose up -d - Install dependencies:
npm install - Configure environment: Update
.envfile - Start development server:
npm run start:dev - Access API documentation: http://localhost:3000/api/docs
The development server supports hot reload, automatically restarting when you make changes to:
- TypeScript files (
.ts) - Environment variables
- Configuration files
- Use
npm run start:debugto enable debugging - Attach your debugger to port 9229
- VS Code debugging configuration is recommended
# Run all unit tests
npm run test
# Run tests in watch mode (development)
npm run test:watch
# Run tests with coverage report
npm run test:cov
# Run end-to-end tests
npm run test:e2e
# Debug tests
npm run test:debug- Unit Tests: Located alongside source files (
.spec.ts) - E2E Tests: Located in
/testdirectory - Coverage Reports: Generated in
/coveragedirectory
- Controllers: API endpoint testing
- Services: Business logic testing
- DTOs: Validation testing
- Authentication: JWT and security testing
- Database: Repository and entity testing
- Write tests for all new features
- Maintain test coverage above 80%
- Use descriptive test names
- Mock external dependencies
- Test both success and error scenarios
# Run ESLint with auto-fix
npm run lint
# Format code with Prettier
npm run format
# Check TypeScript compilation
npm run build- ESLint: TypeScript-first linting with recommended rules
- Prettier: Code formatting for consistent style
- TypeScript: Static type checking
- Husky: Git hooks for pre-commit quality checks (if configured)
- TypeScript strict mode: Enabled for type safety
- No explicit any: Minimized use of
anytype - Consistent formatting: Prettier configuration enforced
- Import organization: Automatic import sorting
- Error handling: Comprehensive error handling patterns
For the best development experience:
- Install ESLint and Prettier extensions
- Enable format-on-save in your IDE
- Use TypeScript language server
- Configure auto-import suggestions
Theme Factory provides comprehensive Swagger/OpenAPI documentation that serves as both documentation and testing interface.
Once the application is running, visit:
http://localhost:3000/api/docs
- Interactive API Explorer: Test endpoints directly from the browser
- Complete Schema Documentation: Detailed request/response models
- Authentication Integration: JWT Bearer token testing
- Real-time Validation: See validation rules and examples
- Error Response Guide: Comprehensive error handling documentation
- Code Examples: Sample requests and responses for all endpoints
- Register a user via
/api/auth/register - Login via
/api/auth/loginto get JWT token - Click "Authorize" button in Swagger UI
- Enter
Bearer YOUR_JWT_TOKEN - Test protected endpoints
POST /api/auth/register- User registrationPOST /api/auth/login- User login
POST /api/users/register- Create new user (admin)GET /api/users- List all usersGET /api/users/:id- Get user detailsPATCH /api/users/:id- Update user
POST /api/themes/create- Create new themeGET /api/themes- List themes (with filtering)GET /api/themes/:id- Get theme detailsPATCH /api/themes/:id- Update themeDELETE /api/themes/:id- Delete theme
π = Requires JWT Bearer token authentication
βββββββββββββββ ββββββββββββββββ
β User β β Theme β
βββββββββββββββ€ ββββββββββββββββ€
β id (UUID) βββββββββββ€ createdById β
β email β β updatedById βββ
β password β β β β
β firstName β β id (UUID) β β
β lastName β β name β β
β isActive β β description β β
β createdAt β β googleFonts β β
β updatedAt β β themeConfig β β
βββββββββββββββ β previewImage β β
β β tags β β
β β isActive β β
β β createdAt β β
ββββββββββββββββββ€ updatedAt β β
ββββββββββββββββ β
βββββββββββ
interface User {
id: string; // UUID primary key
email: string; // Unique email address
password: string; // bcrypt hashed password (excluded from responses)
firstName: string; // User's first name
lastName: string; // User's last name
isActive: boolean; // Account status (default: true)
createdAt: Date; // Account creation timestamp
updatedAt: Date; // Last update timestamp
}interface Theme {
id: string; // UUID primary key
name: string; // Unique theme name
description?: string; // Optional theme description
googleFonts?: string[]; // Array of Google Font names
themeConfig: object; // JSONB - MUI theme configuration
previewImage?: string; // Optional preview image URL
tags?: string[]; // Array of categorization tags
isActive: boolean; // Theme visibility (default: true)
createdById: string; // Foreign key to User
updatedById: string; // Foreign key to User (for audit trail)
createdBy: User; // Relation to creator
updatedBy: User; // Relation to last updater
createdAt: Date; // Creation timestamp
updatedAt: Date; // Last update timestamp
}The themeConfig JSONB field stores complete Material-UI theme options:
interface MuiThemeConfig {
palette?: {
mode?: 'light' | 'dark';
primary?: { main: string; dark?: string; light?: string; };
secondary?: { main: string; dark?: string; light?: string; };
error?: { main: string; };
warning?: { main: string; };
info?: { main: string; };
success?: { main: string; };
};
typography?: {
fontFamily?: string;
fontSize?: number;
h1?: TypographyVariant;
h2?: TypographyVariant;
// ... all MUI typography variants
};
shape?: {
borderRadius?: number;
};
spacing?: number;
shadows?: string[];
transitions?: object;
zIndex?: object;
breakpoints?: object;
components?: object; // MUI component overrides
}- User β Themes: One-to-many (user can create multiple themes)
- Theme β User (Creator): Many-to-one (theme has one creator)
- Theme β User (Updater): Many-to-one (theme has one last updater)
- Audit Trail: All theme modifications track who made the changes
| Variable | Description | Example | Required |
|---|---|---|---|
POSTGRES_PASSWORD |
PostgreSQL password | mySecurePassword123 |
β |
POSTGRES_DB |
Database name | theme_factory_db |
β |
POSTGRES_CONTAINER_NAME |
Docker container name | theme_factory_postgres |
β |
DB_HOST |
Database host | localhost |
β |
DB_PORT |
Database port | 5432 |
β |
DB_USERNAME |
Database username | postgres |
β |
| Variable | Description | Example | Required |
|---|---|---|---|
NODE_ENV |
Application environment | development / production |
β |
PORT |
Server port | 3000 |
β |
HOST_API |
API host URL | http://localhost:3000 |
β |
| Variable | Description | Example | Required |
|---|---|---|---|
JWT_SECRET |
JWT signing secret | your-256-bit-secret |
β |
JWT_EXPIRES_IN |
JWT token expiration | 7d / 24h / 3600s |
β |
NODE_ENV=development
PORT=3000
DB_HOST=localhost
# Enable database logging and synchronizationNODE_ENV=production
PORT=3000
DB_HOST=your-production-db-host
# Disable database synchronization for safety- Never commit
.envfiles to version control - Use strong JWT secrets (256-bit minimum)
- Use complex database passwords
- Set appropriate JWT expiration times
- Use environment-specific configurations
http://localhost:3000/api
POST /api/auth/register
Content-Type: application/json
{
"email": "user@example.com",
"password": "securePassword123",
"firstName": "John",
"lastName": "Doe"
}POST /api/auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "securePassword123"
}Response:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "uuid",
"email": "user@example.com",
"firstName": "John",
"lastName": "Doe"
}
}POST /api/users/register
Authorization: Bearer <jwt_token>
Content-Type: application/jsonGET /api/users?page=1&limit=10
Authorization: Bearer <jwt_token>GET /api/users/:id
Authorization: Bearer <jwt_token>PATCH /api/users/:id
Authorization: Bearer <jwt_token>
Content-Type: application/jsonPOST /api/themes/create
Authorization: Bearer <jwt_token>
Content-Type: application/json
{
"name": "Dark Purple Theme",
"description": "A dark theme with purple accents",
"googleFonts": ["Inter", "Roboto"],
"themeConfig": {
"palette": {
"mode": "dark",
"primary": { "main": "#9c27b0" },
"secondary": { "main": "#ff5722" }
},
"typography": {
"fontFamily": "Inter, sans-serif"
}
},
"tags": ["dark", "purple", "modern"]
}GET /api/themes?page=1&limit=10&search=dark&tags=modern&sortBy=createdAt&sortOrder=DESC
Authorization: Bearer <jwt_token>Query Parameters:
page: Page number (default: 1)limit: Items per page (default: 10)search: Search in theme name and descriptiontags: Filter by tags (comma-separated)createdBy: Filter by creator user IDsortBy: Sort field (createdAt, name, updatedAt)sortOrder: ASC or DESC
GET /api/themes/:id
Authorization: Bearer <jwt_token>PATCH /api/themes/:id
Authorization: Bearer <jwt_token>
Content-Type: application/json
{
"name": "Updated Theme Name",
"description": "Updated description",
"themeConfig": {
// Updated MUI theme configuration
}
}DELETE /api/themes/:id
Authorization: Bearer <jwt_token>All endpoints return consistent error responses:
{
"statusCode": 400,
"message": "Validation failed",
"error": "Bad Request",
"details": [
{
"property": "email",
"constraints": {
"isEmail": "email must be an email"
}
}
]
}Common HTTP Status Codes:
200- Success201- Created400- Bad Request (validation errors)401- Unauthorized (missing/invalid JWT)403- Forbidden (insufficient permissions)404- Not Found409- Conflict (duplicate resource)500- Internal Server Error
π = Requires JWT Bearer token authentication
Complete Documentation: Visit
/api/docsfor interactive Swagger documentation with request/response examples
We welcome contributions to Theme Factory! Here's how to get started:
-
Fork & Clone
git fork theme-factory git clone https://github.com/your-username/theme-factory.git cd theme-factory -
Set Up Development Environment
npm install cp .env.template .env # Configure your .env file docker-compose up -d npm run start:dev -
Create Feature Branch
git checkout -b feature/your-feature-name # or git checkout -b fix/your-bug-fix -
Make Your Changes
- Follow the existing code style
- Add/update tests for new functionality
- Update documentation if needed
- Ensure TypeScript types are properly defined
-
Quality Checks
# Run tests npm run test npm run test:e2e # Check code quality npm run lint npm run format # Build to check for errors npm run build
-
Commit & Push
git add . git commit -m "feat: add your feature description" git push origin feature/your-feature-name
-
Submit Pull Request
- Create PR against the
mainbranch - Provide clear description of changes
- Include screenshots for UI changes
- Reference any related issues
- Create PR against the
- Use TypeScript for all new code
- Follow existing naming conventions
- Add JSDoc comments for public APIs
- Use meaningful variable and function names
- Keep functions small and focused
- Write unit tests for new services and utilities
- Add integration tests for new endpoints
- Maintain test coverage above 80%
- Test both success and error scenarios
- Update Swagger/OpenAPI annotations
- Add code comments for complex logic
- Update README for new features
- Include examples in API documentation
Use conventional commit format:
feat:new featuresfix:bug fixesdocs:documentation updatesstyle:formatting changesrefactor:code refactoringtest:adding testschore:maintenance tasks
- π¨ Theme Features: New MUI theme configuration options
- π Security: Authentication and authorization improvements
- π Analytics: Theme usage tracking and statistics
- π API: New endpoints and functionality
- π§ͺ Testing: Improved test coverage and quality
- π Documentation: Better examples and guides
- π Bug Fixes: Issue resolution and stability improvements
- π¬ Discussions: Use GitHub Discussions for questions
- π Issues: Report bugs via GitHub Issues
- π§ Email: Contact maintainers for security issues
- π Documentation: Check
/api/docsfor API reference
This project is licensed under the UNLICENSED license.
- Install dependencies:
npm install - Configure environment:
cp .env.template .envand update values - Start database:
docker-compose up -d - Start development server:
npm run start:dev - Access API docs: http://localhost:3000/api/docs
- Create a user: POST to
/api/auth/register - Login: POST to
/api/auth/login - Create themes: POST to
/api/themes/createwith JWT token
Database Connection Error
# Check if PostgreSQL is running
docker ps
# Restart database container
docker-compose down
docker-compose up -dPort Already in Use
# Change PORT in .env file or kill process
lsof -ti:3000 | xargs kill -9JWT Token Invalid
- Check JWT_SECRET in .env
- Ensure token is passed as Bearer token
- Check token expiration (JWT_EXPIRES_IN)
Theme Validation Errors
- Refer to MUI theme specification
- Check Swagger docs for exact schema requirements
- Validate color formats (hex values)
For additional help:
- π Check the API documentation at
/api/docs - π Report issues on GitHub
- π¬ Join community discussions
Happy Theme Building! π¨β¨