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
- ๐ 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
- โจ 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
๐จ 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
๐ Quick Start
Installation
# Global installation (recommended)
npm install -g node-apis
# Or use npx (no installation required)
npx node-apis๐จ 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-apisWhy 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๐ก Monorepo users: If you get workspace protocol errors, use
npm install -g node-apisornpx node-apisinstead.
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๐ก 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) - 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)
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 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 codeMulti-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 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 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๐ 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) | |
--framework <framework> |
Web framework to use (express|hono), defaults to express | |
--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)
๐ง 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 deniedSolution: 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 foundSolution: 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:
npm install -g typescript # Global TypeScript
# or in your project
npm install --save-dev typescript๐จ 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
๐ค 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
๐ Changelog
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!"
๐ 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! โจ