Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

node-apis

sobebarali3.7kMIT3.8.1TypeScript support: included

πŸš€ Advanced TypeScript API generator with clean architecture, comprehensive testing, and automatic formatting. Generate production-ready Node.js APIs with complete integration test suites.

api-generator, typescript, nodejs, express, hono, crud, clean-architecture, code-generator, cli, scaffold, boilerplate, performance-monitoring, request-tracing, type-driven, zod, validation, prettier, auto-formatting, production-ready, testing, integration-tests, vitest, supertest, test-generation, tdd, test-driven-development, trpc, type-safety, end-to-end, rpc, procedures, monorepo, destructuring, smart-validation

readme

Node APIs Generator

πŸš€ The most advanced TypeScript API generator for Node.js - Create production-ready API modules with clean architecture, comprehensive testing, and automatic code formatting.

✨ Why Choose Node APIs Generator?

  • πŸš€ Object Destructuring - Modern TypeScript patterns with clean parameter handling
  • 🧠 Intelligent Validation - Automatic Zod schema generation with pattern recognition
  • πŸ“‹ Named Fields - Production-ready default fields instead of empty placeholders
  • πŸ—οΈ Clean Architecture - Controller β†’ Handler β†’ Repository pattern
  • 🌐 Multi-Framework - Support for Express.js and Hono frameworks
  • 🎨 Smart Naming - Accepts any naming format, generates consistent professional code
  • ⚑ Performance Monitoring - Built-in execution timing and request correlation
  • πŸ” Request Tracing - Complete payload logging for easy debugging
  • 🎯 Type-Driven - Intelligent code generation from TypeScript types
  • πŸ”§ TypeScript Strict Mode - Generated code passes strict TypeScript compilation
  • πŸ“¦ Dependency-Free - Generated repositories have zero external dependencies
  • ✨ Auto-Formatting - Prettier integration for consistent code style
  • πŸ”„ Two-Phase Generation - Review types first, then generate code with optimized folder structures
  • 🎯 Smart Interactive Mode - Numbered selection, validation, and existing module handling
  • πŸ§ͺ Comprehensive Testing - Complete integration test suite generated automatically
  • πŸ›‘οΈ Production Ready - Error handling, validation, and observability built-in
  • 🚫 No Service Layer - Direct handler-to-repository pattern for simplicity
  • βš™οΈ Smart Configuration - Set preferences once, skip repetitive prompts
  • πŸ“¦ Zero Config - Works out of the box with sensible defaults

πŸš€ Try It Now!

# Install globally and start building amazing APIs
npm install -g node-apis

# Generate REST APIs
node-apis --name blog --crud --api-style rest --framework express

# Generate tRPC APIs  
node-apis --name user --crud --api-style trpc --framework hono

# Run the comprehensive tests
npm test

⭐ Love this tool? Star it on GitHub and follow @sobebarali for more developer tools!

🎯 What Makes This Different?

Unlike other generators that create static boilerplate, this tool:

  1. Uses modern TypeScript patterns with object destructuring and intelligent type inference
  2. Generates smart validation with automatic Zod schema creation and pattern recognition
  3. Provides production-ready templates with realistic named fields instead of empty placeholders
  4. Parses your TypeScript types and generates intelligent code
  5. Includes performance monitoring and request correlation out of the box
  6. Follows modern clean architecture patterns
  7. Generates working, formatted code that's ready for production
  8. Creates comprehensive test suites with integration tests
  9. Supports iterative development with smart type-driven regeneration

🎨 Smart Naming System

The generator accepts any naming format and automatically converts it to professional, consistent naming conventions:

Input Format Directory Files Classes Variables Constants
user-profile user-profile/ create.userProfile.ts CreateUserProfile userProfile USER_PROFILE
blog_post blog-post/ create.blogPost.ts CreateBlogPost blogPost BLOG_POST
productCategory product-category/ create.productCategory.ts CreateProductCategory productCategory PRODUCT_CATEGORY
OrderHistory order-history/ create.orderHistory.ts CreateOrderHistory orderHistory ORDER_HISTORY

Benefits:

  • βœ… Flexible Input - Use any naming style you prefer
  • βœ… Valid JavaScript - All generated identifiers are syntactically correct
  • βœ… Professional Output - Follows industry-standard naming conventions
  • βœ… Import Safety - No path mismatches or file not found errors

🎨 Choose Your API Style

The generator supports two distinct API paradigms, each optimized for different use cases:

🌐 REST APIs (Traditional HTTP)

  • Best for: Public APIs, microservices, traditional web applications
  • Generates: Controllers, routes, HTTP endpoints with Express/Hono
  • Benefits: Standard HTTP patterns, widely adopted, framework agnostic

πŸš€ tRPC APIs (Type-safe RPC)

  • Best for: Full-stack TypeScript applications, internal APIs, type-safe client-server communication
  • Generates: Procedures, routers, end-to-end type safety
  • Benefits: Auto-completion, compile-time safety, seamless TypeScript integration

Interactive Flow:

πŸš€ Which API style would you like to generate?
  🌐 REST APIs (traditional HTTP endpoints)
  πŸš€ tRPC (type-safe RPC procedures)

πŸ› οΈ  Which web framework would you like to use?
  Express.js (Traditional, widely adopted)  
  Hono (Modern, lightweight, fast)

πŸš€ Quick Start

Installation

# Global installation (recommended)
npm install -g node-apis

# Or use npx (no installation required)
npx node-apis

First-Time Setup (Optional)

Set your framework preference to skip repetitive prompts:

# Interactive setup - choose your preferred framework
node-apis --init-config

# Or set directly
node-apis --set-framework hono  # or express

🚨 Monorepo Users - Important Note

If you're working in a monorepo (pnpm workspaces, Yarn workspaces, npm workspaces) and encounter this error:

npm error Unsupported URL Type "workspace:": workspace:*

Solution: Use global installation to avoid workspace conflicts:

# βœ… Recommended: Install globally
npm install -g node-apis

# βœ… Alternative: Use npx (no installation)
npx node-apis

# βœ… pnpm users: Bypass workspace
pnpm add -g node-apis

# βœ… Yarn users: Global install
yarn global add node-apis

Why this happens: Monorepos use workspace: protocol for local packages, which can conflict with npm registry installations. Global installation bypasses workspace resolution.

Generate Your First API

# Interactive mode - just run the command!
node-apis

# Or specify directly - any naming format works!
node-apis --name user-profile --crud
node-apis --name blog_post --crud
node-apis --name productCategory --crud

# Choose your framework
node-apis --name book --crud --framework express  # Default
node-apis --name book --crud --framework hono     # Lightweight alternative

🎯 Three API Types

The generator supports three distinct API types with optimized folder structures:

1. CRUD APIs (--crud)

Full-stack database operations with HTTP endpoints:

  • Use for: User management, product catalogs, blog posts
  • Generates: Controllers, handlers, repository, validators, routes, tests
  • Pattern: HTTP β†’ Controller β†’ Handler β†’ Repository β†’ Database
  • Folders: controllers/, handlers/, repository/, services/, types/, validators/, routes

2. Custom APIs (--custom)

Business logic operations with HTTP endpoints:

  • Use for: Authentication, notifications, file uploads
  • Generates: Controllers, services, validators, routes, tests
  • Pattern: HTTP β†’ Controller β†’ Service β†’ External APIs/Logic
  • Folders: controllers/, handlers/, repository/, services/, types/, validators/, routes

3. Internal Services (--services) ⭐ Optimized Structure

Third-party integrations for internal use (no HTTP layer):

  • Use for: Payment processing, email services, cloud APIs
  • Generates: Pure service functions, types, comprehensive tests
  • Pattern: Direct function calls β†’ External APIs
  • Folders: Only services/ and types/ (clean & minimal)
  • Import: Use in other modules via import { serviceFunction } from '../module/services/...'

πŸš€ New in v3.5.0: Intelligent Code Generation

🧠 Smart Object Destructuring

Handlers now use modern TypeScript patterns with clean parameter destructuring:

// ✨ Generated handler with object destructuring
export default async function createProductHandler({
  name,
  description,
  status,
  requestId,
}: {
  name: string;
  description: string;
  status: string;
  requestId: string;
}): Promise<typeResult> {
  const product = await create({ name, description, status });
  // ...
}

🎯 Automatic Validation Generation

Smart Zod schema generation with pattern recognition:

// ✨ Generated validator with intelligent patterns
export const payloadSchema = z.object({
  name: z.string(),
  userEmail: z.string().email().optional(), // 🎯 Auto-detected email
  userId: z.string().uuid(), // 🎯 Auto-detected UUID
  phoneNumber: z.string().min(10), // 🎯 Auto-detected phone
  profileUrl: z.string().url().optional(), // 🎯 Auto-detected URL
  description: z.string().optional(),
});

πŸ“‹ Production-Ready Named Fields

No more empty placeholders - every module generates with realistic, useful fields:

// ✨ Generated types with meaningful fields
export type typePayload = {
  name: string; // Universal title/label field
  description?: string; // Common descriptive field
  status?: string; // Useful for state management
  // Add more fields here
};

// ✨ Module-specific IDs
export type typeResultData = {
  productId: string; // Smart ID naming
  name: string;
  description: string | null;
  status: string | null;
  created_at: string;
  updated_at: string;
};

πŸ” Type-Driven Intelligence

The generator analyzes your TypeScript types and generates intelligent code:

  • Smart ID Detection: Automatically uses todoId, userId, productId instead of generic id
  • Optional Field Handling: Proper handling in UPDATE operations (partial updates)
  • Pattern Recognition: Field names trigger appropriate validation (email, URL, phone, UUID)
  • Framework Adaptation: Same intelligent patterns work for both Express.js and Hono

βš™οΈ Configuration

Set your preferences once and skip repetitive prompts:

# Initialize configuration (interactive)
node-apis --init-config

# Set default framework and API style
node-apis --set-framework express
node-apis --set-api-style trpc

# Now generate without specifying preferences
node-apis --name user --crud  # Uses your configured framework and API style

The config file (node-apis.config.json) stores your preferences and is extensible for future features like database ORM selection.

Configuration Workflow Example

# First time setup - choose your preferences interactively
node-apis --init-config
# βœ… Configuration file created successfully!
# πŸš€ Default framework: express, API style: rest

# Change preferences anytime
node-apis --set-framework hono
node-apis --set-api-style trpc
# βœ… Framework set to: hono
# βœ… API style set to: tRPC procedures

# Now generate APIs without specifying preferences
node-apis --name user --crud
# Uses Hono + tRPC from config

# Override config for specific generation
node-apis --name admin --crud --api-style rest --framework express
# Uses Express + REST despite Hono + tRPC being configured

🏒 Monorepo Support

Working in a monorepo? The CLI supports custom target directories so you can generate APIs from any location:

Option 1: Use --target-dir Flag

Generate APIs directly from your monorepo root:

# From monorepo root, generate in apps/server/
node-apis --name user --crud --target-dir apps/server

# From monorepo root, generate in packages/api/
node-apis --name product --crud --target-dir packages/api

# Target directory can be absolute or relative
node-apis --name order --crud --target-dir /path/to/your/backend

Option 2: Global Installation

Install globally to avoid workspace protocol errors:

# βœ… Recommended for monorepos
npm install -g node-apis

# Use from anywhere in your monorepo
cd monorepo-root
node-apis --name user --crud --target-dir apps/api

Option 3: Use npx

Run without installation:

# Always works, no conflicts
npx node-apis --name user --crud --target-dir apps/server

Monorepo Examples

# Nx monorepo
node-apis --name auth --crud --target-dir apps/backend

# Lerna/Rush monorepo
node-apis --name user --crud --target-dir packages/api

# Yarn/pnpm workspaces
node-apis --name product --crud --target-dir services/catalog-api

# Custom structure
node-apis --name notification --services --target-dir infrastructure/email-service

The generated structure will be:

your-target-dir/
└── src/apis/your-module/
    β”œβ”€β”€ controllers/
    β”œβ”€β”€ handlers/
    └── ...

πŸ’‘ Pro Tip: Use global installation (npm install -g node-apis) to avoid workspace conflicts and enable usage from any directory.

That's it! You'll get a complete, production-ready API module with:

  • βœ… Controllers with request logging
  • βœ… Handlers with performance monitoring
  • βœ… Repository with clean data access
  • βœ… TypeScript types and validation
  • βœ… Comprehensive integration test suite
  • βœ… Test configuration (Vitest + Supertest)
  • βœ… Automatic code formatting

πŸ—οΈ Generated Architecture

Your APIs follow a clean, modern architecture with smart naming and comprehensive testing:

src/apis/user-profile/          # kebab-case directories
β”œβ”€β”€ controllers/                # HTTP routing with payload logging
β”‚   β”œβ”€β”€ create.userProfile.ts   # camelCase files β†’ POST /api/user-profiles
β”‚   β”œβ”€β”€ get.userProfile.ts      # GET /api/user-profiles/:id
β”‚   β”œβ”€β”€ list.userProfile.ts     # GET /api/user-profiles
β”‚   β”œβ”€β”€ update.userProfile.ts   # PUT /api/user-profiles/:id
β”‚   └── delete.userProfile.ts   # DELETE /api/user-profiles/:id
β”œβ”€β”€ handlers/                   # Business logic with performance monitoring
β”‚   β”œβ”€β”€ create.userProfile.ts   # βœ… Execution timing
β”‚   β”œβ”€β”€ get.userProfile.ts      # βœ… Error handling
β”‚   └── ...                     # βœ… Request correlation
β”œβ”€β”€ repository/                 # Data access layer
β”‚   └── user-profile.repository.ts # βœ… Clean functions
β”œβ”€β”€ types/                      # TypeScript definitions
β”‚   β”œβ”€β”€ create.userProfile.ts   # βœ… Type-safe payloads
β”‚   └── ...                     # βœ… Result types
β”œβ”€β”€ validators/                 # Zod validation schemas
β”‚   β”œβ”€β”€ create.userProfile.ts   # βœ… Input validation
β”‚   └── ...                     # βœ… Error handling
└── user-profile.routes.ts      # Express/Hono router

tests/user-profile/             # Comprehensive test suite
β”œβ”€β”€ create/
β”‚   β”œβ”€β”€ validation.test.ts      # Input validation tests
β”‚   β”œβ”€β”€ success.test.ts         # Happy path integration tests
β”‚   └── errors.test.ts          # Error handling tests
β”œβ”€β”€ get/
β”‚   └── ... (same pattern for all operations)
└── shared/
    └── helpers.ts              # Test utilities

πŸ’‘ Improved Two-Phase Generation Process

Phase 1: Type Definition & Review

node-apis --name book --crud
# πŸš€ Phase 1: Generating directory structure and type files...
# βœ… Type files generated successfully!

What happens:

  • Creates main module directory and types/ subdirectory only
  • Generates TypeScript type files with placeholder interfaces
  • Shows detailed instructions for each operation type
  • Prompts you to review and customize the typePayload interfaces

Example type file generated:

export type typePayload = {
  // Add your specific fields here
  // name: string;
  // description: string;
  // category?: string;
};

Phase 2: Code Generation & Testing

# After you review types and confirm (type 'yes' or 'y')
# πŸš€ Phase 2: Generating services and repositories...
# πŸ§ͺ Phase 3: Generating comprehensive test suite...

What happens:

  • Creates remaining directories based on API type:
    • Services: Only services/ (no HTTP layer)
    • CRUD/Custom: All folders (controllers, handlers, repository, validators, routes)
  • Generates all code files using your confirmed type definitions
  • Auto-formats all generated code with Prettier
  • Creates comprehensive test suite with validation, success, and error cases

Benefits of Two-Phase Approach

  • 🎯 Type-First Development: Define your data structures before implementation
  • πŸ”§ Customizable: Edit types to match your exact requirements
  • 🚫 No Rework: Generated code uses your confirmed field definitions
  • πŸ“ Clean Structure: Services get minimal folders, APIs get full structure
  • ⚑ Efficient: Only creates what each API type actually needs

πŸ”₯ Generated Code Examples

Controller (HTTP Layer) - Smart Naming in Action

// Input: --name user-profile
// Generated: src/apis/user-profile/controllers/create.userProfile.ts

import { validatePayload } from '../validators/create.userProfile';
import createUserProfileHandler from '../handlers/create.userProfile';

export default async function createUserProfileController(
  req: Request,
  res: Response
): Promise<void> {
  const requestId = (req.headers['x-request-id'] as string) || generateRequestId();

  // Professional naming: USER_PROFILE (CONSTANT_CASE)
  console.info(
    `${requestId} [CONTROLLER] - CREATE USER_PROFILE payload:`,
    JSON.stringify(req.body, null, 2)
  );

  // Validation with detailed error responses
  const validation = validatePayload(req.body);
  if (!validation.success) {
    res.status(400).json({
      data: null,
      error: { code: 'VALIDATION_ERROR', message: validation.error.message, statusCode: 400 },
    });
    return;
  }

  // Call handler with request correlation - PascalCase function names
  const result = await createUserProfileHandler(validation.data, requestId);
  const statusCode = result.error ? result.error.statusCode : 201;
  res.status(statusCode).json(result);
}

Handler (Business Logic) - TypeScript Best Practices

// TypeScript best practice: import type for type-only imports
import type {
  typePayload,
  typeResult,
  typeResultData,
  typeResultError,
} from '../types/create.userProfile';
import create from '../repository/user-profile.repository';

export default async function createUserProfileHandler(
  payload: typePayload,
  requestId: string
): Promise<typeResult> {
  let data: typeResultData | null = null;
  let error: typeResultError | null = null;

  try {
    const startTime = Date.now();
    console.info(`${requestId} [USER_PROFILE] - CREATE handler started`);

    // Direct repository call (no service layer)
    const userProfile = await create(payload);
    data = userProfile;

    const duration = Date.now() - startTime;
    console.info(
      `${requestId} [USER_PROFILE] - CREATE handler completed successfully in ${duration}ms`
    );
  } catch (err) {
    // TypeScript strict mode compatible error handling
    const errorMessage = err instanceof Error ? err.message : 'An unexpected error occurred';
    console.error(`${requestId} [USER_PROFILE] - CREATE handler error: ${errorMessage}`);
    error = {
      code: 'CREATE_FAILED',
      message: errorMessage,
      statusCode: 500,
    };
  }

  return { data, error };
}

Repository (Data Access) - Dependency-Free & Type-Safe

// TypeScript best practice: import type for type-only imports
import type { typePayload as CreatePayload } from '../types/create.userProfile';

export default async function create(payload: CreatePayload) {
  try {
    // TODO: Replace with your database implementation
    // Example: return await db.userProfile.create({ data: payload });

    // Mock implementation - replace with actual database call
    const userProfile = {
      id: `mock-id-${Date.now()}`,
      ...payload,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    };
    return userProfile;
  } catch (error) {
    // TypeScript strict mode compatible - no custom error classes needed
    throw new Error(
      `Database error: Failed to create user profile: ${error instanceof Error ? error.message : 'Unknown error'}`
    );
  }
}

// βœ… No external dependencies - completely self-contained
// βœ… Uses native Error class instead of custom error classes
// βœ… TypeScript strict mode compatible
// βœ… Valid JavaScript identifiers (camelCase variables)

πŸ§ͺ Generated Test Suite

Integration Tests (Focus on Real API Testing)

// tests/book/create-book/success.test.ts
import { describe, it, expect } from 'vitest';
import request from 'supertest';
import app from '../../../src/app';
import { typePayload } from '../../../src/apis/book/types/create.book';

describe('Create Book - Success Tests', () => {
  it('should create book successfully', async () => {
    const payload: typePayload = {
      title: 'Test Book',
      author: 'Test Author',
      metadata: { publisher: 'Test Publisher' },
    };

    const response = await request(app).post('/api/books').send(payload).expect(201);

    expect(response.body.data).toBeDefined();
    expect(response.body.error).toBeNull();
  });
});

Error Handling Tests

// tests/book/create-book/errors.test.ts
describe('Create Book - Error Tests', () => {
  it('should return 400 for invalid payload', async () => {
    const invalidPayload = { invalidField: 'invalid-value' };

    const response = await request(app).post('/api/books').send(invalidPayload).expect(400);

    expect(response.body.data).toBeNull();
    expect(response.body.error.code).toBe('VALIDATION_ERROR');
  });
});

Validation Tests

// tests/book/create-book/validation.test.ts
describe('Create Book - Validation Tests', () => {
  it('should validate required fields', () => {
    const payload: typePayload = {
      title: 'Valid Book',
      author: 'Valid Author',
      metadata: { publisher: 'Valid Publisher' },
    };

    const result = validatePayload(payload);
    expect(result.success).toBe(true);
  });
});

🎯 Usage Examples

Basic CRUD API with Smart Naming

# Any naming format works - the generator handles it intelligently!
node-apis --name user-profile --crud      # kebab-case
node-apis --name blog_post --crud         # snake_case
node-apis --name productCategory --crud   # camelCase
node-apis --name OrderHistory --crud      # PascalCase

# All generate professional, consistent code:
# βœ… 5 endpoints: POST, GET, GET/:id, PUT/:id, DELETE/:id
# βœ… Complete TypeScript types with proper naming
# βœ… Zod validation schemas
# βœ… 15 integration tests (3 per operation)
# βœ… Test configuration (Vitest + Supertest)
# βœ… Performance monitoring
# βœ… Request correlation
# βœ… Auto-formatted code

Multi-Framework Support

# Express.js (default)
node-apis --name user-profile --crud --framework express

# Hono (lightweight alternative)
node-apis --name blog_post --crud --framework hono

# Both generate framework-specific code with consistent naming!

Custom Operations with Tests

# Generate custom user operations
node-apis --name user --custom "login,logout,resetPassword"

# What you get:
# βœ… 3 custom endpoints with full implementation
# βœ… Type-safe request/response interfaces
# βœ… Validation schemas
# βœ… 9 integration tests (3 per operation)
# βœ… Error handling tests
# βœ… Validation tests

Internal Service Operations

# Generate third-party service integrations
node-apis --name stripe --services "createPayment,refund,getPaymentStatus"
node-apis --name sendgrid --services "sendEmail,sendBulkEmail"

# What you get:
# βœ… Pure service functions (no HTTP layer)
# βœ… Clean folder structure (only services/ and types/)
# βœ… Type-safe request/response interfaces
# βœ… Error handling with consistent patterns
# βœ… Comprehensive test suites (validation, success, error cases)
# βœ… Ready for internal use in other modules
# βœ… Template code with TODO comments for easy implementation

Generated Structure for Services:

src/apis/stripe/
β”œβ”€β”€ services/
β”‚   β”œβ”€β”€ createPayment.stripe.ts
β”‚   β”œβ”€β”€ refund.stripe.ts
β”‚   └── getPaymentStatus.stripe.ts
└── types/
    β”œβ”€β”€ createPayment.stripe.ts
    β”œβ”€β”€ refund.stripe.ts
    └── getPaymentStatus.stripe.ts

# No controllers/, handlers/, validators/, repository/ folders
# Services are pure functions for internal use
# Just run the command - it's smart and user-friendly!
node-apis

# 🎯 Smart Features:
# βœ… Numbered selection (works in all terminals)
# βœ… Existing module detection with smart options
# βœ… Enhanced validation with helpful examples
# βœ… Clear visual feedback with emojis and formatting

# πŸ”„ Interactive Flow:
# 1. πŸ” Detect existing modules (if any)
# 2. πŸ“ Enter module name with validation
# 3. 🎯 Choose API type (1-3 numbered selection):
#    1. πŸ—ƒοΈ  CRUD operations (Create, Read, Update, Delete)
#    2. ⚑ Custom API operations (Business logic endpoints)
#    3. πŸ”§ Internal service operations (Third-party integrations)
# 4. πŸ“‹ Enter operation names with smart validation
# 5. πŸš€ Choose API style (REST or tRPC) - NEW!
# 6. βš™οΈ  Framework selection (Express or Hono)
# 7. 🚨 Handle existing modules:
#    β€’ πŸ”„ Overwrite existing module (replace all files)
#    β€’ βž• Add operations to existing module
#    β€’ ❌ Cancel generation
# 8. ✨ Two-phase generation with type review
# 9. πŸ§ͺ Comprehensive test suite generation

🎯 Interactive Mode Benefits

  • Terminal Compatible: Numbered selection works everywhere
  • Smart Validation: Helpful examples and error messages
  • Existing Module Handling: Never accidentally overwrite work
  • Visual Feedback: Emojis and clear formatting
  • Type-First: Review and customize types before code generation

Type-Driven Development with Smart Naming

# 1. Generate types first (any naming format!)
node-apis --name product_category --crud

# 2. Edit the types (add your fields)
# Edit: src/apis/product-category/types/create.productCategory.ts

# 3. Code and tests automatically use your exact types!
# All generated code is type-safe and uses consistent naming:
# - Directory: product-category/ (kebab-case)
# - Files: create.productCategory.ts (camelCase)
# - Classes: CreateProductCategoryController (PascalCase)
# - Variables: productCategory (camelCase)
# - Constants: PRODUCT_CATEGORY (CONSTANT_CASE)

Run Your Tests

# Run all tests
npm test

# Run tests for specific module
npm run test:module -- product

# Run with coverage
npm run test:coverage

# Watch mode for development
npm run test:watch

πŸ”₯ tRPC Support - Type-Safe APIs Made Easy

New in v3.6.1: Enhanced tRPC procedures with consistent error handling and improved type safety!

🎯 What is tRPC Style?

tRPC (TypeScript Remote Procedure Call) provides end-to-end type safety from your backend to frontend. Instead of traditional REST endpoints, you get type-safe procedure calls with automatic validation.

πŸš€ Quick tRPC Example

# Generate tRPC procedures instead of REST controllers
node-apis --name blog --crud --trpc-style

# Set tRPC as your default style
node-apis --set-trpc-style true
node-apis --name user --crud  # Uses tRPC style

πŸ—οΈ tRPC vs REST Structure Comparison

tRPC Style REST Style
src/apis/blog/ src/apis/blog/
β”œβ”€β”€ procedures/ β”œβ”€β”€ controllers/
β”œβ”€β”€ handlers/ β”œβ”€β”€ handlers/
β”œβ”€β”€ repository/ β”œβ”€β”€ repository/
β”œβ”€β”€ types/ β”œβ”€β”€ types/
β”œβ”€β”€ validators/ β”œβ”€β”€ validators/
└── blog.router.ts └── blog.routes.ts

🎯 Generated tRPC Code Examples

tRPC Procedure (procedures/create.blog.ts)

import { publicProcedure } from '../../../trpc';
import { payloadSchema } from '../validators/create.blog';
import createBlogHandler from '../handlers/create.blog';
import type { typePayload } from '../types/create.blog';

export const createBlogProcedure = publicProcedure
  .input(payloadSchema)                    // 🎯 Automatic validation
  .mutation(async ({ input }: { input: typePayload }) => {  // 🎯 Enhanced type safety
    const requestId = generateRequestId();

    try {
      return await createBlogHandler({     // 🎯 Same business logic
        ...input,
        requestId,
      });
    } catch (error) {                      // πŸ›‘οΈ Consistent error handling
      return {
        data: null,
        error: {
          code: 'INTERNAL_ERROR',
          message: error instanceof Error ? error.message : 'Something went wrong',
          statusCode: 500,
          requestId
        }
      };
    }
  });

tRPC Router (blog.router.ts)

import { router } from '../../trpc';
import { createBlogProcedure } from './procedures/create.blog';
import { getBlogProcedure } from './procedures/get.blog';
// ...

export const blogRouter = router({
  create: createBlogProcedure,             // 🎯 Procedure mapping
  get: getBlogProcedure,
  list: listBlogsProcedure,
  update: updateBlogProcedure,
  delete: deleteBlogProcedure,
});

export type BlogRouter = typeof blogRouter; // 🎯 Type export

πŸ”§ Required tRPC Setup

To use the generated tRPC code, you'll need to set up tRPC in your project:

1. Install Dependencies

npm install @trpc/server @trpc/client zod

2. Create tRPC Setup (src/trpc/index.ts)

import { initTRPC } from '@trpc/server';

const t = initTRPC.create();

export const router = t.router;
export const publicProcedure = t.procedure;

// Main app router
import { blogRouter } from '../apis/blog/blog.router';

export const appRouter = router({
  blog: blogRouter,
  // Add more modules here
});

export type AppRouter = typeof appRouter;

3. Express Integration (src/server.ts)

import express from 'express';
import { createExpressMiddleware } from '@trpc/server/adapters/express';
import { appRouter } from './trpc';

const app = express();

app.use(
  '/trpc',
  createExpressMiddleware({
    router: appRouter,
  })
);

app.listen(3000);

πŸš€ Client Usage Examples

Next.js Client

import { createTRPCNext } from '@trpc/next';
import type { AppRouter } from '../server/trpc';

export const trpc = createTRPCNext<AppRouter>({
  config() {
    return { url: '/api/trpc' };
  },
});

// In a React component
function BlogManager() {
  const createBlog = trpc.blog.create.useMutation();
  const { data: blogs } = trpc.blog.list.useQuery({ page: 1 });

  const handleCreate = async () => {
    const result = await createBlog.mutateAsync({
      name: 'My Blog Post',       // βœ… Type-safe
      description: 'Great post!', // βœ… Auto-complete
      status: 'published',        // βœ… Validated
    });

    if (result.data) {
      console.log('Created:', result.data.blogId); // βœ… Type inference
    }
  };

  return (
    <div>
      <button onClick={handleCreate}>Create Blog</button>
      {blogs?.data?.items.map(blog => (
        <div key={blog.blogId}>{blog.name}</div>
      ))}
    </div>
  );
}

🎯 Key Benefits of tRPC Style

βœ… End-to-End Type Safety

// Full TypeScript inference
const blog = await trpc.blog.create.mutate({
  name: "Post Title",     // βœ… Type-safe
  description: "Content", // βœ… Optional field
  // status: 123          // ❌ TypeScript error!
});

// Automatic return type inference
blog.data?.blogId;        // βœ… string
blog.data?.created_at;    // βœ… string

βœ… Enhanced Error Handling (New in v3.6.1)

// Consistent error format across all procedures
const result = await trpc.blog.create.mutate({ name: "Test" });

if (result.error) {
  console.log(result.error.code);        // βœ… 'INTERNAL_ERROR'
  console.log(result.error.message);     // βœ… Descriptive error message
  console.log(result.error.statusCode);  // βœ… HTTP status code
  console.log(result.error.requestId);   // βœ… Request tracing ID
}

βœ… Same Business Logic

The handlers, repository, and types are identical to REST - only the transport layer changes!

βœ… Smart Validation

// Automatic Zod validation
trpc.blog.create.mutate({
  name: "",               // ❌ Validation error
  description: null,      // ❌ Type error
});

βœ… Performance Benefits

  • Direct procedure calls (no HTTP overhead)
  • Built-in caching with React Query
  • Automatic request deduplication
  • Optimistic updates support

🎯 When to Use Each Style

Use tRPC Style When:

  • βœ… Full-stack TypeScript projects
  • βœ… Team values type safety
  • βœ… Modern development workflow
  • βœ… React/Next.js frontend
  • βœ… API consumed primarily by your own frontend

Use REST Style When:

  • βœ… Public APIs for third parties
  • βœ… Multiple different client technologies
  • βœ… Traditional HTTP/JSON APIs
  • βœ… OpenAPI/Swagger documentation needed

πŸ“‹ tRPC Configuration

Set tRPC as your default style:

# Set tRPC style preference
node-apis --set-trpc-style true

# Now all generations use tRPC style by default
node-apis --name user --crud     # Uses tRPC procedures
node-apis --name auth --custom "login,logout"  # Uses tRPC procedures

# Override for specific generation
node-apis --name public-api --crud --framework express  # Uses REST despite tRPC config

πŸ”₯ Complete tRPC Example

Generate a complete blog API with tRPC:

# Generate blog API with tRPC style (new syntax)
node-apis --name blog --crud --api-style trpc --framework express

# Or using deprecated syntax (shows warning)
node-apis --name blog --crud --trpc-style

# What you get:
# βœ… 5 tRPC procedures (create, get, list, update, delete)
# βœ… Type-safe validation with Zod schemas
# βœ… Business logic handlers with object destructuring
# βœ… Repository functions for data access
# βœ… TypeScript types for requests/responses
# βœ… Complete test suite for all operations
# βœ… tRPC router combining all procedures
# βœ… Production-ready code with error handling

Generated structure:

src/apis/blog/
β”œβ”€β”€ procedures/           # πŸ†• tRPC procedures
β”‚   β”œβ”€β”€ create.blog.ts
β”‚   β”œβ”€β”€ get.blog.ts
β”‚   └── ...
β”œβ”€β”€ handlers/             # βœ… Same business logic
β”œβ”€β”€ repository/           # βœ… Same data access
β”œβ”€β”€ types/               # βœ… Same TypeScript types
β”œβ”€β”€ validators/          # βœ… Same Zod schemas (perfect for tRPC!)
└── blog.router.ts       # πŸ†• tRPC router

This is a complete, production-ready tRPC API generated in seconds! πŸŽ‰

πŸ“‹ Command Line Options

Option Alias Description
--name <name> -n Module name (skips interactive prompt)
--crud | Generate CRUD operations (create, get, list, update, delete)
--custom <names> | Generate custom operations (comma-separated)
--services <names> | Generate internal service operations (comma-separated)
--api-style <style> | API style to generate (rest|trpc), defaults to rest πŸ†•
--framework <framework> | Web framework to use (express|hono), defaults to express
--target-dir <dir> | Target directory for generated files (default: current directory)
--set-api-style <style> | Set default API style in config (rest|trpc) πŸ†•
--set-framework <framework> | Set default framework in config (express|hono)
--trpc-style | ⚠️ Deprecated: Use --api-style trpc instead
--set-trpc-style <bool> | ⚠️ Deprecated: Use --set-api-style instead
--force -f Overwrite existing files
--no-interactive | Skip interactive prompts
--init-config | Initialize configuration file
--version -V Show version number
--help -h Show help information

🎨 What Makes the Generated Code Special?

βœ… Performance Monitoring Built-In

req-1703123456789-abc123 [BOOK] - CREATE handler started
req-1703123456789-abc123 [BOOK] - CREATE handler completed successfully in 45ms

βœ… Complete Request Tracing

req-1703123456789-abc123 [CONTROLLER] - CREATE BOOK payload: {
  "title": "The Great Gatsby",
  "author": "F. Scott Fitzgerald"
}

βœ… Production-Ready Error Handling

{
  "data": null,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Title is required",
    "statusCode": 400
  }
}

βœ… Type-Safe Throughout

  • Controllers know exact request/response types
  • Handlers use your custom field definitions
  • Repositories match your data structure
  • Validators enforce your business rules

πŸ›‘οΈ Production-Ready Error Handling

Defense in Depth Architecture (New in v3.6.1)

The generator now implements comprehensive error handling across all API layers, ensuring your applications are resilient and production-ready:

Complete Coverage Across All Layers

🌐 API Entry Points
β”œβ”€β”€ πŸ›‘οΈ Controllers (Express/Hono) - Framework & validation errors
β”œβ”€β”€ πŸ›‘οΈ tRPC Procedures - Procedure-level errors (NEW!)
β”œβ”€β”€ πŸ›‘οΈ Handlers - Business logic errors  
└── πŸ›‘οΈ Repository - Data access errors

Consistent Error Format

All layers return the same standardized error structure:

{
  data: null,
  error: {
    code: 'VALIDATION_ERROR' | 'NOT_FOUND' | 'INTERNAL_ERROR',
    message: 'Descriptive error message',
    statusCode: 400 | 404 | 500,
    requestId: 'req-abc123...' // For request tracing
  }
}

Enhanced tRPC Error Handling

// Every tRPC procedure now includes robust error handling
export const createUserProcedure = publicProcedure
  .input(payloadSchema)
  .mutation(async ({ input }: { input: typePayload }) => {
    const requestId = randomBytes(16).toString('hex');

    try {
      return await createUserHandler({ ...input, requestId });
    } catch (error) {
      // Consistent error format with request tracing
      return {
        data: null,
        error: {
          code: 'INTERNAL_ERROR',
          message: error instanceof Error ? error.message : 'Something went wrong',
          statusCode: 500,
          requestId // Essential for debugging
        }
      };
    }
  });

Benefits of This Approach

  • πŸ” Request Tracing: Every error includes a requestId for debugging
  • πŸ”„ Consistency: Same error format across Express, Hono, and tRPC
  • πŸ›‘οΈ Reliability: Prevents unhandled promise rejections
  • πŸ“Š Monitoring: Structured errors perfect for logging systems
  • 🎯 Production Ready: Built for real-world application requirements

πŸš€ Advanced Features

Smart Type-Driven Generation

  • Parses your TypeScript types and generates matching code
  • Regenerates handlers when you update type definitions
  • Maintains consistency between types and implementation
  • Tests automatically use your exact types for complete type safety

Comprehensive Testing

  • Integration tests only - focus on real API behavior
  • No complex mocking - tests actual endpoints with supertest
  • Type-safe tests - all tests use your TypeScript types
  • Complete coverage - validation, success, and error scenarios
  • Ready-to-run - includes Vitest configuration and scripts

Automatic Code Formatting

  • Prettier integration formats all generated code
  • Consistent style across your entire codebase
  • No manual formatting needed

Clean Architecture

  • No service layer bloat - direct handler-to-repository pattern
  • Single responsibility - each layer has a clear purpose
  • Easy to test - clean separation of concerns
  • Performance monitoring built into every handler

Developer Experience

  • Interactive CLI that guides you through the process
  • Smart defaults that work out of the box
  • Incremental development - add operations to existing modules
  • Type safety throughout the entire stack
  • Test-driven development ready out of the box

πŸ“¦ Requirements

  • Node.js >= 16.0.0
  • TypeScript project (the generator creates TypeScript files)

πŸ”§ Troubleshooting

Common Issues and Solutions

🚨 Workspace Protocol Error (Monorepo Users)

npm error Unsupported URL Type "workspace:": workspace:*

Solution: Install globally to avoid workspace conflicts:

npm install -g node-apis  # βœ… Recommended
# or
npx node-apis            # βœ… No installation needed

🚨 Permission Denied (macOS/Linux)

Error: EACCES: permission denied

Solution: Use sudo or fix npm permissions:

sudo npm install -g node-apis  # Quick fix
# or
npm config set prefix ~/.npm-global  # Better long-term solution

🚨 Command Not Found After Global Install

bash: node-apis: command not found

Solution: Check your PATH or use npx:

npx node-apis  # Always works
# or
echo $PATH     # Check if npm global bin is in PATH

🚨 TypeScript Compilation Errors in Generated Code

Solution: Ensure you have TypeScript installed and compatible version:

npm install -g typescript  # Global TypeScript
# or in your project
npm install --save-dev typescript

Note: Generated code is compatible with TypeScript strict mode and follows best practices:

  • Uses import type for type-only imports
  • Proper error handling with instanceof Error checks
  • Valid JavaScript identifiers for all variable names

🚨 Tests Failing After Generation

Solution: Install test dependencies:

npm install --save-dev vitest supertest @types/supertest

πŸ’‘ Pro Tips

  • Always use global installation for CLI tools like node-apis
  • Use npx if you prefer not to install globally
  • Check the generated files - they include helpful TODO comments
  • Customize the types first before generating the full code
  • Generated code is TypeScript strict mode ready - no compilation errors
  • No external dependencies - generated repositories are completely self-contained
  • Use any naming format - the smart naming system handles everything

🀝 Contributing

We welcome contributions! Here's how:

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

πŸ“‹ Changelog

v3.6.1 - Enhanced Error Handling & Type Safety πŸ›‘οΈ

πŸ”₯ Major Enhancement: Consistent Error Handling

  • βœ… Enhanced tRPC Procedures: Added try-catch blocks to all tRPC procedure templates
  • βœ… Type Safety Improvements: Explicit typePayload typing in all procedures
  • βœ… Consistent Error Format: All procedures return standardized error structure
  • βœ… Defense in Depth: Complete error handling coverage across all API layers
  • βœ… Request Tracing: Request IDs included in all error responses for debugging
  • βœ… Production Ready: Prevents unhandled promise rejections and crashes

v3.5.1 - tRPC Integration & Monorepo Support πŸš€

πŸ”₯ Major Feature: tRPC Support

  • βœ… tRPC Style Generation: Generate tRPC procedures instead of REST controllers
  • βœ… Type-Safe APIs: Full end-to-end type safety from backend to frontend
  • βœ… CLI Integration: --trpc-style flag and --set-trpc-style configuration
  • βœ… Smart Templates: New tRPC procedure, router, and test templates
  • βœ… Same Business Logic: Reuses existing handlers, repository, types, and validators
  • βœ… Conditional Generation: Switch between tRPC and REST styles seamlessly

🏒 Monorepo Support

  • βœ… Target Directory: --target-dir flag for generating in specific directories
  • βœ… Flexible Paths: Support for absolute and relative target paths
  • βœ… Root Generation: Generate APIs from monorepo root without cd commands
  • βœ… Global Installation: Improved compatibility with workspace protocols

🎯 Enhanced Developer Experience

  • βœ… Interactive tRPC Setup: Prompts for setting tRPC style preference
  • βœ… Configuration Management: Persistent tRPC style settings in config file
  • βœ… Comprehensive Documentation: Complete tRPC setup and usage examples
  • βœ… Performance Benefits: Direct procedure calls with built-in validation

v3.5.0 - Major Code Generation Revolution πŸŽ‰

🧠 Handler Destructuring Revolution

  • βœ… Modern TypeScript Patterns: All handlers now use object destructuring
  • βœ… Clean Parameter Handling: ({ name, email, requestId }: HandlerParams) => {}
  • βœ… Type-Safe Function Signatures: Full TypeScript inference and validation
  • βœ… Repository Consistency: Matching destructuring patterns across all layers

πŸ” Intelligent Validation & Auto-Population

  • βœ… Smart Pattern Recognition: Email, URL, phone, UUID auto-detection
  • βœ… Realistic Default Fields: name, description, status in every module
  • βœ… Module-Specific IDs: todoId, userId, productId instead of generic id
  • βœ… Enhanced Type System: Better optional field handling in UPDATE operations

πŸ—οΈ Framework & Architecture Improvements

  • βœ… Hono Compatibility: Full support for Hono framework with destructuring
  • βœ… Express Enhancement: Improved Express.js templates with modern patterns
  • βœ… Clean Architecture: Refined handler β†’ repository pattern
  • βœ… Type-First Development: Types drive intelligent code generation

✨ Developer Experience & Quality

  • βœ… Production-Ready Code: Realistic fields and professional patterns
  • βœ… Zero Configuration Issues: All generated code passes strict TypeScript
  • βœ… Smart Naming: Consistent professional naming across all generated files
  • βœ… Enhanced Testing: Tests automatically use exact type definitions

v3.1.6 - TypeScript & Build Fixes πŸ”§

πŸ”§ Critical Fixes:

  • βœ… TypeScript Strict Mode: Fixed 'error' is of type 'unknown' compilation errors
  • βœ… Variable Naming: Fixed invalid JavaScript identifiers in generated repository code
  • βœ… Build Stability: All generated code now passes strict TypeScript compilation
  • βœ… Error Handling: Improved error handling patterns for better type safety

🎨 Code Quality Improvements:

  • βœ… Import Type: All templates now use import type for type-only imports (TypeScript best practice)
  • βœ… Dependency-Free: Removed shared errors dependency from generated repositories
  • βœ… Smart Variables: Variable names now use camelCase regardless of input format

v3.1.5 - Critical Bug Fix πŸ›

πŸ”§ Critical Fix:

  • βœ… Module Import Error: Fixed Cannot find module 'test-config-generator.service' error
  • βœ… Package Stability: Temporarily disabled test config generation to ensure package works
  • βœ… Global Installation: Package now works correctly when installed globally

v3.1.4 - Bug Fix Release πŸ›

πŸ”§ Critical Fix:

  • βœ… Missing Module Fix: Fixed missing test-config-generator.service in published package
  • βœ… Import Resolution: Resolved module import errors when using the npm package globally

v3.1.3 - Smart Naming System 🎨

πŸŽ‰ Major Enhancement: Smart Naming Transformation

  • βœ… Flexible Input: Accept any naming format (kebab-case, snake_case, camelCase, PascalCase)
  • βœ… Professional Output: Generate consistent, industry-standard naming conventions
  • βœ… Import Safety: Eliminate path mismatches and file not found errors
  • βœ… Framework Consistency: Works seamlessly with both Express and Hono

πŸ”§ Technical Improvements:

  • βœ… Template System: Updated all templates for consistent naming
  • βœ… Path Resolution: Fixed CLI path generation bugs
  • βœ… Code Quality: Professional naming throughout generated code
  • βœ… Error Prevention: No more invalid JavaScript identifiers

πŸ“ Examples:

# All of these work perfectly now!
node-apis --name user-profile --crud      # β†’ user-profile/ directory
node-apis --name blog_post --crud         # β†’ blog-post/ directory
node-apis --name productCategory --crud   # β†’ product-category/ directory

πŸ“„ License

MIT License - see the LICENSE file for details.

πŸŽ‰ Why Developers Love This Tool

"Finally, a code generator that creates code I actually want to use in production!"

"The smart naming system is incredible - I can use any naming style and get perfect output!"

"The comprehensive test suite saved me days of writing tests manually."

"The performance monitoring and request tracing saved me hours of debugging."

"Clean architecture out of the box - no more service layer spaghetti!"

"The type-driven approach is genius - my handlers always match my data structure."

"Integration tests that actually test the real API - brilliant!"

"No more worrying about naming conventions - the generator handles it all professionally!"

"The generated code passes TypeScript strict mode without any errors - amazing!"

πŸ“Š What You Get

For CRUD APIs:

  • πŸ—οΈ 22 files generated (5 operations Γ— 4 files + routes + repository)
  • πŸ§ͺ 15 integration tests (3 per operation)
  • ⚑ Production-ready with monitoring and error handling
  • 🎯 Type-safe throughout the entire stack

For Custom APIs:

  • πŸ—οΈ NΓ—4 files generated (N operations Γ— 4 files + routes + repository)
  • πŸ§ͺ NΓ—3 integration tests (3 per operation)
  • ⚑ Production-ready with monitoring and error handling
  • 🎯 Type-safe throughout the entire stack

πŸ“‹ Configuration File

The node-apis.config.json file stores your preferences:

{
  "version": "1.0.0",
  "framework": "express",
  "trpcStyle": false,
  "database": {
    "orm": "prisma",
    "type": "postgresql"
  },
  "preferences": {
    "autoFormat": true,
    "generateTests": true,
    "skipConfirmation": false
  }
}

Configuration Options

  • framework: Web framework (express | hono)
  • trpcStyle: Generate tRPC procedures instead of REST controllers (true | false)
  • database: Database settings (future feature)
    • orm: ORM preference (prisma | typeorm | drizzle)
    • type: Database type (postgresql | mysql | sqlite)
  • preferences: Generation preferences
    • autoFormat: Auto-format generated code
    • generateTests: Generate test files
    • skipConfirmation: Skip confirmation prompts

Configuration Benefits

  • πŸš€ Faster Workflow - Skip repetitive framework selection prompts
  • πŸ‘₯ Team Consistency - Share config files across team members
  • πŸ”§ Flexible Override - CLI options still work to override config
  • πŸ“ˆ Future-Proof - Extensible for database ORM and other preferences
  • πŸ’Ύ Persistent - Settings saved locally per project

Ready to generate amazing APIs with comprehensive tests? πŸš€

npm install -g node-apis
node-apis --name book --crud
npm test  # Run your generated tests!

πŸ‘¨β€πŸ’» About the Author

Hi! I'm Sobebar Ali, a passionate Backend Developer and Founding AI Engineer at Capri AI. I built this tool to solve the repetitive task of creating production-ready API modules with proper architecture, comprehensive testing, and modern TypeScript patterns.

🎯 Why I Built This Tool

After years of building APIs professionally, I noticed developers spending too much time on boilerplate code instead of business logic. This generator bridges that gap by providing:

  • Production-ready code that follows industry best practices
  • Comprehensive testing that actually tests your APIs
  • Type-safe patterns that prevent runtime errors
  • Clean architecture that scales with your project

🌟 Connect with Me

πŸ’ Support This Project

If this tool saves you development time and helps your team build better APIs:

  • ⭐ Star this repository on GitHub
  • πŸ“¦ Share it with your development team
  • πŸ› Report issues or suggest features
  • πŸ’– Follow me for more developer tools and insights

🀝 Contributing

I welcome contributions! Whether it's:

  • πŸ› Bug fixes
  • ✨ New features (like tRPC support!)
  • πŸ“š Documentation improvements
  • πŸ§ͺ Test enhancements

Check out the contribution guidelines to get started.


Happy coding and testing! ✨

"Building this tool has been a journey of solving real developer problems. I hope it saves you as much time as it has saved me and my team!" - Sobebar Ali

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[3.6.1] - 2025-01-13

πŸ›‘οΈ Enhanced Error Handling & Type Safety

This release strengthens the generated code with consistent error handling patterns and improved type safety across all API entry points.

πŸ”§ tRPC Procedures Improvements

  • βœ… Consistent Error Handling: Added try-catch blocks to all tRPC procedure templates

    • Create, Get, List, Update, Delete, and Generic procedures now handle errors consistently
    • All procedures return standardized error format: { data: null, error: { code, message, statusCode, requestId } }
    • Error handling now matches the pattern used in Express/Hono controllers
  • 🎯 Enhanced Type Safety: Improved typePayload usage in tRPC procedures

    • All procedures now explicitly type the input parameter: async ({ input }: { input: typePayload })
    • Better TypeScript intellisense and compile-time error checking
    • Consistent type imports across all procedure templates

πŸ—οΈ Defense in Depth Error Handling

Complete Error Handling Coverage:

  • Controllers βœ… - Handle validation and framework-level errors
  • tRPC Procedures βœ… - Handle procedure-level errors (NEW)
  • Handlers βœ… - Handle business logic errors
  • Repository βœ… - Handle data access errors

🎯 Benefits

  • πŸ”„ Consistency: All API entry points return the same { data, error } format
  • πŸ” Traceability: Request IDs included in all error responses
  • πŸ›‘οΈ Reliability: Prevents unhandled promise rejections from crashing the app
  • 🎯 Framework Agnostic: Same error handling regardless of Express/tRPC
  • πŸ“Š Monitoring: Consistent error format for logging and monitoring systems

πŸ“‹ Updated Error Patterns

// tRPC Procedure with Enhanced Error Handling
export const createUserProcedure = publicProcedure
  .input(payloadSchema)
  .mutation(async ({ input }: { input: typePayload }) => {
    const requestId = randomBytes(16).toString('hex');

    try {
      return await createUserHandler({
        ...input,
        requestId,
      });
    } catch (error) {
      return {
        data: null,
        error: {
          code: 'INTERNAL_ERROR',
          message: error instanceof Error ? error.message : 'Something went wrong',
          statusCode: 500,
          requestId
        }
      };
    }
  });

πŸ”„ Breaking Changes

None - this is a backward-compatible enhancement to existing templates.

πŸ“š Documentation

  • Updated README with error handling strategy discussion
  • Added comprehensive error handling examples
  • Documented the defense-in-depth approach

[3.6.0] - 2025-01-13

🎨 Major Interactive CLI Enhancement - API Style Selection

This release introduces a fundamental improvement to the CLI workflow with the addition of API Style Selection, giving developers clear choice between REST and tRPC paradigms while maintaining full backward compatibility.

πŸš€ New API Style Selection

  • 🎨 Clear API Style Choice: New interactive step to choose between REST and tRPC
    πŸš€ Which API style would you like to generate?
      🌐 REST APIs (traditional HTTP endpoints)
      πŸš€ tRPC (type-safe RPC procedures)
  • 🧩 Separate Framework Choice: Framework selection (Express/Hono) is now independent of API style
  • βš™οΈ Enhanced Configuration: Save both API style and framework preferences independently

πŸ› οΈ New CLI Commands

  • Primary Commands:

    • --api-style <style> - Choose between rest or trpc (NEW)
    • --set-api-style <style> - Save API style preference to config (NEW)
  • Enhanced Interactive Flow:

    1. Module name β†’ API type β†’ API style β†’ Framework β†’ Generation
    2. Smart prompting only when no preferences are saved
    3. Independent preference management for style and framework

πŸ“‹ Command Examples

# New syntax (recommended)
node-apis --name user --crud --api-style trpc --framework express
node-apis --name blog --crud --api-style rest --framework hono

# Configuration management
node-apis --set-api-style trpc
node-apis --set-framework express

# Interactive mode with enhanced flow
node-apis  # Now includes API style selection step

πŸ”„ Backward Compatibility

  • ⚠️ Deprecated but Working: --trpc-style flag still works with deprecation warnings
  • πŸ”§ Automatic Migration: Old configs with trpcStyle: true automatically convert to apiStyle: 'trpc'
  • πŸ“‹ Graceful Transition: All existing commands continue to work without breaking changes

🎯 User Experience Improvements

  • 🧠 Better Mental Model: Clear separation between "what kind of API" (REST/tRPC) and "what framework" (Express/Hono)
  • πŸ’Ύ Smart Configuration: Only prompts for missing preferences, saves choices independently
  • πŸ” Enhanced Discoverability: tRPC is prominently featured as an equal option to REST

πŸ—οΈ Technical Implementation

  • πŸ“¦ Type System Updates: New SupportedApiStyle type alongside existing SupportedFramework
  • πŸ”§ Service Functions: New getEffectiveApiStyle(), setApiStyle(), and related prompt functions
  • βœ… Validation Enhancement: Config validation now includes API style checking
  • πŸ”„ Template Integration: Seamless integration with existing template system

πŸ› Bug Fixes

  • 🏒 Monorepo Support: Enhanced --target-dir handling with better TypeScript strict mode compatibility
  • βš™οΈ Config Management: Improved error handling and validation for configuration files

πŸ“š Documentation

  • πŸ“– Updated README: Comprehensive documentation of new API style feature
  • 🎯 Enhanced Examples: Updated all examples to showcase new CLI syntax
  • πŸ“‹ Command Reference: Complete CLI options table with new commands and deprecation notices

[3.5.0] - 2025-01-03

πŸŽ‰ Major Code Generation Revolution

This release represents a massive leap forward in code quality, type safety, and developer experience. We've completely redesigned the code generation system with intelligent templates, automatic validation, and modern TypeScript patterns.

πŸš€ Revolutionary Handler System

  • Object Destructuring Parameters: All handlers now use clean object destructuring instead of positional parameters
    // Before: createHandler(payload, requestId)
    // After: createHandler({ name, description, status, requestId })
  • Type-Safe Parameter Handling: Full TypeScript inference with proper field-level destructuring
  • Consistent API Patterns: Unified parameter patterns across all handlers and repositories

🧠 Intelligent Validation System

  • Automatic Zod Schema Generation: Smart conversion from TypeScript types to validation schemas
  • Pattern Recognition: Automatic email, URL, phone, and UUID validation based on field names
  • Field-Specific Validation:
    • userEmail β†’ z.string().email().optional()
    • userId β†’ z.string().uuid()
    • phoneNumber β†’ z.string().min(10)
    • profileUrl β†’ z.string().url()

πŸ“‹ Production-Ready Default Fields

  • Named Field Templates: No more empty placeholders - every module generates with realistic fields
    export type typePayload = {
      name: string;
      description?: string;
      status?: string;
      // Add more fields here
    };
  • Module-Specific IDs: Smart ID naming (todoId, userId, productId) instead of generic id
  • Consistent Field Patterns: Same meaningful fields across CREATE, GET, UPDATE, LIST operations

🎯 Enhanced Type System

  • Smart ID Field Detection: Automatically detects todoId, userId, etc. with fallback to generic id
  • Optional Field Handling: Proper optional/required field management in UPDATE operations
  • Type-Driven Code Generation: All code generated based on actual TypeScript type definitions

πŸ”§ Framework Integration Improvements

  • Express.js Support: Enhanced Express controller generation with proper type imports
  • Hono Framework Support: Full Hono integration with context-based parameter handling
  • Unified API Patterns: Consistent code generation regardless of framework choice

⚑ Developer Experience Enhancements

  • Immediate Usability: Generated code works out-of-the-box with realistic examples
  • Copy-Paste Ready: Perfect starting point for real-world development
  • Learning Tool: Demonstrates TypeScript and API design best practices
  • Smart Comments: Helpful guidance for customization and extension

πŸ—οΈ Architecture Improvements

  • Two-Phase Generation: Types first, then intelligent code generation based on parsed types
  • Template Consistency: All templates follow the same modern patterns
  • Error Prevention: Better type safety prevents common runtime errors
  • Maintainable Code: Generated code follows clean architecture principles

πŸ“Š Performance & Quality

  • Faster Generation: Optimized template system for quicker code generation
  • Better IntelliSense: Enhanced TypeScript support with proper type inference
  • Cleaner Output: More readable and maintainable generated code
  • Consistent Formatting: All code properly formatted with Prettier integration

πŸ”„ Breaking Changes

  • Handler Signatures: Updated to use object destructuring (automatic migration)
  • ID Field Names: Now uses module-specific IDs like todoId instead of generic id
  • Validator Templates: Now generate actual validation schemas instead of placeholders

πŸ› οΈ Migration Guide

Existing projects can regenerate modules with --force flag to get the new improvements. The enhanced templates are backward compatible but provide significantly better developer experience.

[3.4.0] - 2024-12-19

πŸŽ‰ Major Interactive Mode Improvements

βœ… Fixed Critical Issues

  • Fixed API Type Selection Navigation: Replaced broken arrow key navigation with reliable numbered selection (1-3)
  • Fixed Services Interactive Mode: Users can now properly select and generate service operations interactively
  • Fixed Custom Operations Interactive Mode: Custom API operations now work correctly in interactive mode

πŸš€ New Interactive Features

  • Interactive Force Override: Smart handling of existing modules with three options:
    • πŸ”„ Overwrite existing module (replace all files)
    • βž• Add operations to existing module (append mode)
    • ❌ Cancel generation
  • Enhanced Operation Name Validation: Comprehensive validation for custom and service operation names:
    • Validates camelCase format (e.g., sendEmail, getUserProfile)
    • Checks for reserved words and invalid characters
    • Provides helpful error messages and examples
    • Enforces length limits (2-50 characters)
  • Improved User Experience:
    • Added emojis and better visual formatting
    • Clear examples and helpful tips for operation naming
    • Better error messages and validation feedback

πŸ”§ Technical Improvements

  • Numbered Selection System: Reliable terminal-compatible selection for all environments
  • Enhanced Type Safety: Improved TypeScript interfaces for all prompt responses
  • Better Error Handling: Graceful fallbacks and comprehensive error recovery
  • Interactive Config Management: Foundation for future config management features

πŸ“Š Feature Parity Achieved

  • CLI vs Interactive: All CLI functionality now available in interactive mode
  • Services Support: Full interactive support for service operations
  • Custom Operations: Complete interactive support for custom API operations
  • CRUD Operations: Existing CRUD interactive support maintained

πŸ§ͺ Testing & Validation

  • Comprehensive testing across different terminal environments
  • Validated all three API types (CRUD, Custom, Services) in interactive mode
  • Confirmed proper folder structure generation for each API type
  • Verified two-phase generation workflow for all operation types

[3.3.1] - 2024-01-07

Fixed

  • πŸ—οΈ Service Folder Structure: Services now create only necessary folders (services/ and types/) instead of all API folders

    • Before: Services created unnecessary controllers/, handlers/, validators/, repository/ folders
    • After: Services create only services/ and types/ folders for cleaner architecture
    • Impact: Cleaner project structure for internal service operations
  • ⚑ Two-Phase Generation Flow: Fixed generation workflow to properly separate type creation from code generation

    • Phase 1: Now creates only main directory + types/ subdirectory, generates type files
    • User Review: Prompts user to review and confirm generated types before proceeding
    • Phase 2: After confirmation, creates remaining directories and generates all other files
    • Impact: Better user experience with type customization before full code generation
  • πŸ”§ CLI Integration: Fixed interactive mode to respect API types provided via command line flags

    • Before: Always prompted for API type even when provided via --crud, --custom, or --services
    • After: Only prompts for missing information, respects CLI-provided API types
    • Impact: Smoother CLI experience with fewer redundant prompts

Technical Improvements

  • Enhanced getModuleSubdirectories() to accept API type parameter for conditional directory creation
  • Added generateModuleStructurePhase1() and generateModuleStructurePhase2() functions
  • Updated interactive flow to handle pre-provided API types correctly
  • Improved type safety with exact optional property types

Examples

# Services now create clean structure
node-apis --name stripe --services "createPayment,refund"
# Creates: src/apis/stripe/services/ and src/apis/stripe/types/ only

# Two-phase flow for all API types
node-apis --name user --crud
# Phase 1: Creates types/ and prompts for review
# Phase 2: Creates all remaining folders after confirmation

[3.3.0] - 2024-01-07

Added

  • New API Type: Internal Service Operations (--services)
    • Generate third-party API integrations for internal use
    • Pure service functions without HTTP layer (no controllers, validators, routes)
    • Consistent type patterns with existing CRUD/Custom APIs
    • Comprehensive test generation (validation, success, error cases)
    • Template code with TODO comments for easy implementation
    • Perfect for payment processing, email services, cloud APIs

Features

  • CLI Support: Added --services <names> flag for service generation
  • Interactive Mode: Added "Internal service operations" option in prompts
  • Service Templates: Complete template system for service generation
  • Test Generation: Full test suite generation for service modules
  • Type Consistency: Uses same typePayload/typeResult pattern as CRUD/Custom
  • Documentation: Updated README with service examples and three API types explanation

Technical Implementation

  • Added service templates (services.templates.ts, services.tests.ts)
  • Updated CLI commands and prompts to support services
  • Enhanced two-phase generator for service module generation
  • Added 'services' directory to module subdirectories
  • Updated type definitions for service operations

Examples

# Generate payment service
node-apis --name stripe --services "createPayment,refund,getPaymentStatus"

# Generate email service
node-apis --name sendgrid --services "sendEmail,sendBulkEmail"

[3.2.1] - 2024-01-07

Fixed

  • Critical Bug: Fixed Hono framework controller generation
    • All CRUD controllers (get, list, update, delete) were incorrectly generating Express.js code when Hono framework was selected
    • Only the create controller was properly using Hono framework
    • Custom controllers were also affected by the same issue
    • All controllers now correctly generate framework-specific code (Hono vs Express)
    • Custom routes now properly use Hono app instead of Express router when Hono is selected

Technical Details

  • Fixed generateGetControllerContent, generateListControllerContent, generateUpdateControllerContent, and generateDeleteControllerContent functions to respect framework parameter
  • Fixed generateCustomControllerContent and generateGenericCustomControllerContent to support Hono framework
  • Fixed generateCustomRouteContent and generateGenericRouteContent to use correct framework imports and syntax
  • Updated two-phase generator to pass framework parameter to custom controller generation

[3.2.0] - 2024-01-07

Added

  • Configuration System: New node-apis.config.json configuration file support
    • Set default framework preference to avoid repetitive prompts
    • Extensible configuration structure for future features (database ORM, etc.)
    • CLI commands: --init-config and --set-framework <framework>
    • Interactive framework selection with option to save preferences
    • CLI framework override still works when config exists

Enhanced

  • Developer Experience: Eliminates framework selection prompts in interactive mode when configured
  • CLI Options: Added --init-config and --set-framework commands
  • Documentation: Updated README with configuration examples and options

Technical Details

  • New config service with TypeScript strict type safety
  • Config validation and error handling
  • Merge functionality for updating existing configurations
  • Framework precedence: CLI option > Config file > Default (express)

[3.1.6] - Previous Release

Features

  • Clean Architecture (Controller β†’ Handler β†’ Repository)
  • Multi-framework support (Express.js and Hono)
  • Smart naming conventions
  • Performance monitoring and request tracing
  • Type-driven code generation
  • Comprehensive integration testing
  • Two-phase generation process
  • Auto-formatting with Prettier
  • Zero external dependencies in generated code