npm package: @machize/create-stack-fastify
Description: 🚀 A powerful CLI tool for generating production-ready Fastify projects with TypeScript, Clean Architecture, and Domain-Driven Design
Author: Márcio Zebedeu
Latest version: 1.0.23

# Create Stack Fastify

[![npm version](https://badge.fury.io/js/@machize/create-stack-fastify.svg)](https://badge.fury.io/js/@machize/create-stack-fastify)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

🚀 **A powerful CLI tool for generating production-ready Fastify projects with TypeScript, following Clean Architecture and Domain-Driven Design principles.**

## 🌟 Features

- ⚡ **Fast Setup**: Generate a complete project structure in seconds
- 🏗️ **Clean Architecture**: Follows Clean Architecture and DDD patterns
- 🔧 **TypeScript First**: Full TypeScript support with type safety
- 🚀 **Fastify Framework**: Built on top of the fastest Node.js web framework
- 📊 **Database Support**: Choose between TypeORM or Prisma ORM
- 📚 **API Documentation**: Automatic Swagger/OpenAPI documentation generation
- 🔍 **GraphQL Ready**: Optional GraphQL support with schema generation
- 🔐 **Authentication**: Built-in JWT authentication system with RSA key support
- 📧 **Email Service**: Integrated email service with template support
- 🧪 **Testing Ready**: Pre-configured testing environment with Jest
- 📦 **Module System**: Modular architecture for better code organization
- 🌐 **Internationalization**: Full English language support with comprehensive documentation
- 🔧 **Content-Type Handling**: Enhanced request parsing with automatic Content-Type detection
- 🛠️ **Error Handling**: Improved GraphQL error handling with automatic redirects
- 🤝 **Open Source**: MIT licensed and open for contributions

## 📋 Prerequisites

Before you begin, ensure you have the following installed:
- **Node.js** (version 16 or higher)
- **npm** or **yarn** package manager

## 🚀 Quick Start

### Installation

You can use `@machize/machize/create-stack-fastifyy with npm/yarn without global installation:

```bash
# Using npm
npx @machize/create-stack-fastify api

# Using yarn
yarn create @machize/create-stack-fastify api
```

### Usage

```bash
@machize/machize/create-stack-fastify-name> api [--module=module-name]
```

**Parameters:**
- `project-name`: The name of your new project
- `api`: Command to create a Fastify API project
- `--module` (optional): Add additional modules to your project

**Examples:**
```bash
# Creates project with default 'users' module (includes TypeScript files)
npx @machize/create-stack-fastify  api

# Creates project with 'users' + 'products' modules
npx @machize/create-stack-fastify api --module=products

# Add new module to existing project
npx @machize/create-stack-fastify project --module=orders
```

### Interactive Setup

During project creation, you'll be prompted to choose the tools you want to include:

```
? Which tools would you like to use?
❯ ◯ TypeORM
  ◯ Prisma
  ◯ Swagger
  ◯ GraphQL
```

**Available Options:**
- **TypeORM**: Object-Relational Mapping with decorators
- **Prisma**: Modern database toolkit with type-safe client
- **Swagger**: Automatic API documentation generation
- **GraphQL**: GraphQL API with schema-first approach

## 📁 Project Structure

The generated project follows a clean, modular architecture based on Clean Architecture and DDD principles:

```
my-project/
├── .husky/                   # Git hooks configuration
├── prisma/                  # Prisma schema and migrations (if selected)
│   └── schema.prisma        # Database schema definition
├── tests/                   # Test files and utilities
├── uploads/                 # File upload directory
├── src/
│   ├── config/              # Application configuration
│   │   ├── client/          # External service clients
│   │   ├── swaggers/        # Swagger documentation files
│   │   │   ├── components/  # Swagger components
│   │   │   └── specification/ # API specifications
│   │   ├── column.ts        # Database column configurations
│   │   ├── constants.ts     # Application constants
│   │   ├── graphql.config.ts # GraphQL configuration (if selected)
│   │   └── typeorm.connection.ts # TypeORM config (if selected)
│   ├── shared/              # Shared utilities and types
│   │   ├── common/          # Common utilities
│   │   ├── domain/          # Domain-specific shared code
│   │   ├── interfaces/      # Shared interfaces
│   │   ├── types/           # Type definitions
│   │   └── utils/           # Utility functions
│   └── core/                # Core business logic
│       ├── infra/           # Shared infrastructure layer
│       │   ├── adapter/     # External service adapters
│       │   │   ├── adapterFastify.ts    # Fastify adapter
│       │   │   └── httpResponse.ts      # HTTP response utilities
│       │   ├── graphql/     # GraphQL infrastructure (if selected)
│       │   │   ├── schema/      # GraphQL schema files
│       │   │   └── resolvers.ts # Main resolvers file
│       │   ├── http/        # HTTP infrastructure
│       │   │   ├── handlers/    # Route handlers
│       │   │   ├── middlewares/ # Custom middlewares
│       │   │   ├── v1/routers/  # API route definitions
│       │   │   ├── app.ts       # Fastify application setup
│       │   │   ├── httpServer.ts # HTTP server configuration
│       │   │   ├── server.ts    # Main server entry point
│       │   │   ├── swagger.ts   # Swagger setup (if selected)
│       │   │   └── openapidocs.ts # OpenAPI documentation
│       │   ├── plugins/     # Infrastructure plugins
│       │   │   ├── swagger.plugins.ts   # Swagger plugin
│       │   │   └── mercurius.plugins.ts # GraphQL plugin
│       │   ├── prisma/      # Prisma client (if selected)
│       │   │   └── prisma-client.ts
│       │   └── typeorm/     # TypeORM entities (if selected)
│       │       └── entities/
│       └── [module-name]/   # Domain modules (e.g., users, orders)
│           ├── application/ # Application layer
│           │   ├── services/    # Application services
│           │   │   ├── auth/    # Authentication services
│           │   │   ├── mail/    # Mail services
│           │   │   └── user/    # User services
│           │   └── usecases/    # Use cases/interactors
│           │       ├── auth/    # Authentication use cases
│           │       └── user/    # User use cases
│           ├── domain/      # Domain layer
│           │   ├── auth/        # Auth domain entities and DTOs
│           │   └── user/        # User domain entities and DTOs
│           ├── mappers/     # Data transformation mappers
│           ├── model/       # Data models
│           ├── module/      # Module configuration and DI
│           ├── plugins/     # Module-specific plugins
│           ├── repositories/ # Data access repositories
│           ├── service/     # Domain services
│           └── [module].resolver.ts # GraphQL resolver (if GraphQL enabled)
├── .env                     # Environment variables
├── package.json             # Project dependencies and scripts
├── tsconfig.json            # TypeScript configuration
├── README.md                # Project documentation
├── GRAPHQL_EXAMPLES.md      # GraphQL usage examples (if selected)
├── SWAGGER_TYPEORM_EXAMPLES.md # Swagger + TypeORM examples (if selected)
└── LIBRARIES_EXAMPLES.md    # Library usage examples
```

## 🔧 Generated Files and Features

### Core Features

1. **HTTP Server**: Fastify-based HTTP server with type safety and enhanced content parsing
2. **Authentication System**: JWT-based authentication with RSA key support and middleware
3. **Database Integration**: Ready-to-use database connections with migration support
4. **API Documentation**: Auto-generated Swagger documentation with interactive UI
5. **Error Handling**: Centralized error handling with proper HTTP responses and GraphQL redirects
6. **Logging**: Structured logging with different levels and request tracking
7. **Environment Configuration**: Environment-based configuration management with .env support
8. **RSA Key Management**: Automatic RSA key generation and configuration scripts
9. **Content-Type Detection**: Smart content parsing for different media types
10. **International Support**: Full English documentation and comments

### Authentication System

The generated project includes a complete authentication system:

- **JWT Token Management**: Secure token generation and validation
- **User Registration**: Sign-up with email validation
- **User Login**: Secure authentication endpoint
- **Protected Routes**: Middleware for route protection
- **Password Hashing**: Bcrypt-based password security

### Database Support

#### TypeORM Integration
- Entity definitions with decorators
- Repository pattern implementation
- Migration system support
- Connection pooling and configuration

#### Prisma Integration
- Schema-first database modeling
- Type-safe database client
- Automatic migration generation
- Intuitive query interface

### API Documentation

When Swagger is enabled, the project includes:
- Automatic OpenAPI schema generation
- Interactive API documentation at `/docs`
- JSON schema endpoint at `/docs/json`
- Request/response validation
- Authentication documentation

### GraphQL Support

When GraphQL is enabled, you get:
- GraphQL schema definition
- Resolver implementation templates
- GraphiQL playground at `/graphiql`
- Type-safe GraphQL operations
- Integration with your chosen ORM

## 🏃‍♂️ Getting Started with Your Project

After creating your project:

1. **Navigate to your project**:
   ```bash
   cd my-project
   ```

2. **Install dependencies** (automatically done during creation):
   ```bash
   yarn install
   # or
   npm install
   ```

3. **Configure your environment**:
   ```bash
   cp .env.example .env
   # Edit .env with your configuration
   ```

4. **Set up your database**:
   - For TypeORM: Configure `src/config/typeorm.connection.ts`
   - For Prisma: Edit `prisma/schema.prisma`

5. **Run database migrations** (if applicable):
   ```bash
   # For TypeORM
   yarn typeorm migration:run
   
   # For Prisma
   yarn prisma migrate dev
   ```

6. **Start the development server**:
   ```bash
   yarn dev
   # or
   npm run dev
   ```

7. **Access your application**:
   - API: `http://localhost:3021`
   - Health Check: `http://localhost:3021/healthcheck`
   - Swagger UI: `http://localhost:3021/docs` (if enabled)
   - GraphiQL: `http://localhost:3021/graphiql` (if enabled)

## 📚 Available Scripts

The generated project includes these npm scripts:

```bash
# Development
yarn dev          # Start development server with hot reload
yarn build        # Build the project for production
yarn start        # Start production server

# Testing
yarn test         # Run test suite
yarn test:watch   # Run tests in watch mode
yarn test:coverage # Run tests with coverage report

# Linting and Formatting
yarn lint         # Run ESLint
yarn lint:fix     # Fix ESLint issues automatically
yarn format       # Format code with Prettier

# Database (varies by ORM choice)
yarn typeorm      # TypeORM CLI commands
yarn prisma       # Prisma CLI commands
```

## 🔐 Environment Configuration

The project uses environment variables for configuration. Create a `.env` file in your project root:

```env
# Server Configuration
PORT=3021
NODE_ENV=development

# Database Configuration
DATABASE_URL="postgresql://username:password@localhost:5432/database"

# JWT Configuration
JWT_SECRET="your-super-secret-jwt-key"
JWT_EXPIRES_IN="7d"

# Email Configuration (if using email service)
SMTP_HOST="smtp.gmail.com"
SMTP_PORT=587
SMTP_USER="your-email@gmail.com"
SMTP_PASS="your-app-password"

# External Services
REDIS_URL="redis://localhost:6379"
```

## 🧪 Testing

The project is set up for testing with Jest and includes:

- Unit test examples
- Integration test templates
- Test utilities and helpers
- Coverage reporting
- Mock implementations

## 📖 API Examples

### REST API Examples

```typescript
// GET /api/v1/users
// Response: List of users

// POST /api/v1/auth/signup
{
  "email": "user@example.com",
  "password": "securePassword123",
  "name": "John Doe"
}

// POST /api/v1/auth/signin
{
  "email": "user@example.com",
  "password": "securePassword123"
}
```

### GraphQL Examples (if enabled)

```graphql
# Query: Get all users
query GetUsers {
  users {
    id
    email
    name
    createdAt
  }
}

# Mutation: Create user
mutation CreateUser {
  createUser(input: {
    email: "user@example.com"
    name: "John Doe"
    password: "securePassword123"
  }) {
    id
    email
    name
  }
}
```

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.

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

## 📝 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 👨‍💻 Author

**Márcio Zebedeu**
- GitHub: [@zebedeu](https://github.com/zebedeu)
- Email: support@clinicapro.ao

## 📝 Recent Updates

### v1.0.3 - Internationalization and Enhanced Features
- ✅ **Full English Translation**: All Portuguese text translated to English
- ✅ **Enhanced Documentation**: Comprehensive RSA key setup guide
- ✅ **Improved Error Handling**: Better GraphQL error responses with automatic redirects
- ✅ **Content-Type Enhancement**: Smart parsing for requests without Content-Type headers
- ✅ **Code Comments**: All code comments translated to English for better accessibility
- ✅ **Template Updates**: All template files now use English documentation

## 🙏 Acknowledgments

- [Fastify](https://www.fastify.io/) - Fast and low overhead web framework
- [TypeScript](https://www.typescriptlang.org/) - Typed superset of JavaScript
- [TypeORM](https://typeorm.io/) - Amazing ORM for TypeScript
- [Prisma](https://www.prisma.io/) - Next-generation ORM
- [Swagger](https://swagger.io/) - API documentation tools
- [GraphQL](https://graphql.org/) - Query language for APIs

## 📊 Project Stats

- **Language**: TypeScript
- **Framework**: Fastify
- **Architecture**: Clean Architecture + DDD
- **Package Manager**: Yarn/NPM
- **Minimum Node.js**: v16+

---

⭐ **Star this project if you find it helpful!**

📢 **Follow the project for updates and new features**