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
- ๐ง 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
- ๐งช 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
๐ฏ 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-apisFirst-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-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โ๏ธ Configuration
Set your preferences once and skip repetitive prompts:
# Initialize configuration (interactive)
node-apis --init-config
# Set default framework
node-apis --set-framework express
node-apis --set-framework hono
# Now generate without specifying framework
node-apis --name user --crud # Uses your configured frameworkThe 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 preferred framework
node-apis --init-config
# โ
Configuration file created successfully!
# ๐ Default framework: express (or hono if you chose it interactively)
# Change framework preference anytime
node-apis --set-framework hono
# โ
Framework set to: hono
# Now generate APIs without specifying framework
node-apis --name user --crud
# Uses Hono framework from config
# Override config for specific generation
node-apis --name admin --crud --framework express
# Uses Express despite Hono being configured๐ก 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) - 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 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 and compatible version:
npm install -g typescript # Global TypeScript
# or in your project
npm install --save-dev typescriptNote: Generated code is compatible with TypeScript strict mode and follows best practices:
- Uses
import typefor type-only imports - Proper error handling with
instanceof Errorchecks - 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:
- 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.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 typefor 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.servicein 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",
"database": {
"orm": "prisma",
"type": "postgresql"
},
"preferences": {
"autoFormat": true,
"generateTests": true,
"skipConfirmation": false
}
}Configuration Options
framework: Web framework (express|hono)database: Database settings (future feature)orm: ORM preference (prisma|typeorm|drizzle)type: Database type (postgresql|mysql|sqlite)
preferences: Generation preferencesautoFormat: Auto-format generated codegenerateTests: Generate test filesskipConfirmation: 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!Happy coding and testing! โจ