JSPM

  • Created
  • Published
  • Downloads 17
  • Score
    100M100P100Q85613F
  • License MIT

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

Package Exports

  • node-apis
  • node-apis/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (node-apis) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

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?

  • ๐Ÿ—๏ธ Clean Architecture - Controller โ†’ Handler โ†’ Repository pattern
  • โšก 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
  • โœจ Auto-Formatting - Prettier integration for consistent code style
  • ๐Ÿ”„ Two-Phase Generation - Review types first, then generate code
  • ๐Ÿงช 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
  • ๐Ÿ“ฆ Zero Config - Works out of the box with sensible defaults

๐ŸŽฏ What Makes This Different?

Unlike other generators that create static boilerplate, this tool:

  1. Parses your TypeScript types and generates intelligent code
  2. Includes performance monitoring and request correlation out of the box
  3. Follows modern clean architecture patterns
  4. Generates working, formatted code that's ready for production
  5. Creates comprehensive test suites with integration tests
  6. Supports iterative development with smart type-driven regeneration

๐Ÿš€ Quick Start

Installation

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

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

Generate Your First API

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

# Or specify directly
node-apis --name book --crud

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 comprehensive testing:

src/apis/book/
โ”œโ”€โ”€ controllers/        # HTTP routing with payload logging
โ”‚   โ”œโ”€โ”€ create.book.ts  # POST /api/books
โ”‚   โ”œโ”€โ”€ get.book.ts     # GET /api/books/:id
โ”‚   โ”œโ”€โ”€ list.book.ts    # GET /api/books
โ”‚   โ”œโ”€โ”€ update.book.ts  # PUT /api/books/:id
โ”‚   โ””โ”€โ”€ delete.book.ts  # DELETE /api/books/:id
โ”œโ”€โ”€ handlers/           # Business logic with performance monitoring
โ”‚   โ”œโ”€โ”€ create.book.ts  # โœ… Execution timing
โ”‚   โ”œโ”€โ”€ get.book.ts     # โœ… Error handling
โ”‚   โ””โ”€โ”€ ...             # โœ… Request correlation
โ”œโ”€โ”€ repository/         # Data access layer
โ”‚   โ””โ”€โ”€ book.repository.ts # โœ… Clean functions
โ”œโ”€โ”€ types/              # TypeScript definitions
โ”‚   โ”œโ”€โ”€ create.book.ts  # โœ… Type-safe payloads
โ”‚   โ””โ”€โ”€ ...             # โœ… Result types
โ”œโ”€โ”€ validators/         # Zod validation schemas
โ”‚   โ”œโ”€โ”€ create.book.ts  # โœ… Input validation
โ”‚   โ””โ”€โ”€ ...             # โœ… Error handling
โ””โ”€โ”€ book.routes.ts      # Express router

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

๐Ÿ’ก Three-Phase Generation Process

Phase 1: Types First

node-apis --name book --crud
# Generates type files and asks for confirmation

Phase 2: Code Generation

# After you review and confirm types (type 'yes')
# Generates controllers, handlers, repositories, validators
# All code is automatically formatted with Prettier

Phase 3: Test Generation

# Automatically generates comprehensive test suite
# โœ… Integration tests for all endpoints
# โœ… Validation tests for all inputs
# โœ… Error handling tests
# โœ… Test configuration (Vitest + Supertest)

๐Ÿ”ฅ Generated Code Examples

Controller (HTTP Layer)

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

  // Complete payload logging for debugging
  console.info(`${requestId} [CONTROLLER] - CREATE BOOK 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
  const result = await createBookHandler(validation.data, requestId);
  const statusCode = result.error ? result.error.statusCode : 201;
  res.status(statusCode).json(result);
}

Handler (Business Logic)

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

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

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

    const duration = Date.now() - startTime;
    console.info(`${requestId} [BOOK] - CREATE handler completed successfully in ${duration}ms`);
  } catch (err) {
    const customError = err as any;
    console.error(`${requestId} [BOOK] - CREATE handler error: ${customError.message}`);
    error = {
      code: customError.errorCode ?? 'INTERNAL_ERROR',
      message: customError.message ?? 'An unexpected error occurred',
      statusCode: customError.statusCode ?? 500,
    };
  }

  return { data, error };
}

Repository (Data Access)

export default async function create(payload: CreatePayload) {
  try {
    // Your database implementation here
    const book = {
      id: `book-${Date.now()}`,
      ...payload,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    };
    return book;
  } catch (error) {
    throw new DatabaseError(`Failed to create book: ${error instanceof Error ? error.message : 'Unknown error'}`);
  }
}

๐Ÿงช 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 Tests

# Generate a complete book API
node-apis --name book --crud

# What you get:
# โœ… 5 endpoints: POST, GET, GET/:id, PUT/:id, DELETE/:id
# โœ… Complete TypeScript types
# โœ… Zod validation schemas
# โœ… 15 integration tests (3 per operation)
# โœ… Test configuration (Vitest + Supertest)
# โœ… Performance monitoring
# โœ… Request correlation
# โœ… Auto-formatted code

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
# Just run the command - it's smart!
node-apis

# The CLI will:
# 1. ๐Ÿ” Detect existing modules
# 2. ๐Ÿค” Ask what you want to do
# 3. ๐Ÿ“ Guide you through the process
# 4. โœจ Generate beautiful, working code
# 5. ๐Ÿงช Create comprehensive test suite

Type-Driven Development

# 1. Generate types first
node-apis --name product --crud

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

# 3. Code and tests automatically use your exact types!
# All generated code is type-safe and consistent

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

๐Ÿ“‹ 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)
--force -f Overwrite existing files
--no-interactive Skip interactive prompts
--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

๐Ÿš€ 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)

๐Ÿค 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

๐Ÿ“„ 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 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!"

๐Ÿ“Š 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

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

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

Happy coding and testing! โœจ