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:
- Parses your TypeScript types and generates intelligent code
- Includes performance monitoring and request correlation out of the box
- Follows modern clean architecture patterns
- Generates working, formatted code that's ready for production
- Creates comprehensive test suites with integration tests
- 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-apisGenerate Your First API
# Interactive mode - just run the command!
node-apis
# Or specify directly
node-apis --name book --crudThat'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 confirmationPhase 2: Code Generation
# After you review and confirm types (type 'yes')
# Generates controllers, handlers, repositories, validators
# All code is automatically formatted with PrettierPhase 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 codeCustom 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 testsInteractive Mode (Recommended)
# 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 suiteType-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 consistentRun 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:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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! โจ