difisoft-nodejs-22-common-openapi-generator
v1.0.2
Published
TypeScript library for generating OpenAPI specifications from endpoint definitions
Downloads
35
Maintainers
Readme
Common OpenAPI Generator
A TypeScript library for generating OpenAPI 3.0 specifications from endpoint definitions with support for OAuth2 security schemes, scope management, and customizable generation.
Features
V2 - TypeScript Compiler API (Recommended)
- 🚀 IDE-like Analysis: Uses TypeScript Compiler API for accurate type analysis
- 🔍 Method Signature Analysis: Automatically extracts input/output types from method signatures
- 📁 Project-aware: Analyzes entire TypeScript projects with proper import resolution
- 🎯 Path Parameter Detection: Automatically detects path parameters from URI patterns like
{id} - 🔍 Query Parameter Extraction: Extracts query parameters for GET/DELETE methods
- 📝 Request Body Detection: Automatically determines when request body is needed
- 🛠️ Zero Configuration: Works out of the box with sensible defaults
- 🔧 Type-safe: Full TypeScript support with comprehensive type definitions
V1 - Legacy (Regex-based)
- 🚀 Easy Integration: Simple API for generating OpenAPI specifications
- 🔐 OAuth2 Support: Built-in OAuth2 security scheme generation with scope management
- 🎯 Flexible Configuration: Highly configurable with custom generators and schemas
- 📝 TypeScript Support: Full TypeScript support with comprehensive type definitions
- 🛠️ CLI Interface: Command-line interface for build-time generation
- 🔧 Extensible: Support for custom generators and schema definitions
- 📊 Auto-detection: Automatic detection of resources and generation of appropriate schemas
- 🔍 RequestHandler Integration: Seamless integration with common-kafkajs RequestHandler
- 📄 TypeScript File Support: Directly processes TypeScript RequestHandler files without compilation
- 🧠 Method Signature Analysis: Automatically analyzes method signatures for better schema generation
- ⚡ Zero Configuration: Works out of the box with sensible defaults
Installation
# Using yarn (recommended)
yarn add common-openapi
# Using npm
npm install common-openapiQuick Start
V2 - TypeScript Compiler API (Recommended)
import { OpenApiGeneratorV2 } from 'common-openapi';
// Create generator with project path
const generator = new OpenApiGeneratorV2('/path/to/your/project');
// Generate from RequestHandler (automatically analyzes TypeScript)
await generator.generateAndSave(
'/path/to/RequestHandler.ts',
'./openapi.json'
);V1 - Legacy Usage
import { OpenApiGenerator } from 'common-openapi';
// Create generator with no configuration (uses sensible defaults)
const generator = new OpenApiGenerator();
// Add endpoints
generator.addEndpoints([
{
uri: 'get:/api/v1/users',
handler: 'getUsers'
},
{
uri: 'post:/api/v1/users',
handler: 'createUser'
}
]);
// Generate and save OpenAPI specification
await generator.generateAndSave('openapi.json');With Custom Configuration
import { OpenApiGenerator } from 'common-openapi';
// Create generator with custom configuration
const generator = new OpenApiGenerator({
info: {
title: 'My API',
version: '1.0.0',
description: 'My awesome API'
},
scopeGroup: 'MyService'
});
// Add endpoints
generator.addEndpoints([
{
uri: 'get:/api/v1/users',
handler: 'getUsers'
},
{
uri: 'post:/api/v1/users',
handler: 'createUser'
}
]);
// Generate and save OpenAPI specification
await generator.generateAndSave('openapi.json');Using with RequestHandler (from common-kafkajs)
import { OpenApiGenerator } from 'common-openapi';
import { Container } from 'typedi';
import RequestHandler from './RequestHandler';
// Configure container and get RequestHandler
const requestHandler = Container.get(RequestHandler);
// Create generator
const generator = new OpenApiGenerator({
info: {
title: 'Favourist Manager API',
version: '1.0.0',
description: 'API for managing user favourites'
},
scopeGroup: 'FavouristManager'
});
// Generate OpenAPI specification directly from RequestHandler
// This automatically analyzes method signatures and generates proper schemas
await generator.generateFromRequestHandlerAndSave(requestHandler, 'openapi.json');Using with TypeScript RequestHandler Files
The CLI supports directly processing TypeScript RequestHandler files without compilation:
# Generate from TypeScript RequestHandler file
npx common-openapi --endpoints src/RequestHandler.ts --output openapi.json
# With configuration
npx common-openapi --config config.json --endpoints src/RequestHandler.ts --output openapi.json
# Using yarn
yarn common-openapi --endpoints src/RequestHandler.ts --output openapi.jsonThe library automatically:
- Parses the TypeScript file without requiring compilation
- Extracts the
matchingList()method from the RequestHandler class - Generates OpenAPI specification from the endpoints
- Supports both
.tsand.jsfiles
Advanced RequestHandler Integration
The library can automatically analyze your RequestHandler's method signatures to generate more accurate OpenAPI specifications:
import { OpenApiGenerator } from 'common-openapi';
import { Container } from 'typedi';
import RequestHandler from './RequestHandler';
// Configure your application
configureLogger(config.logger.config);
configureContainer();
// Get RequestHandler from container
const requestHandler = Container.get(RequestHandler);
// Create generator with detailed configuration
const generator = new OpenApiGenerator({
info: {
title: 'My Service API',
version: '1.0.0',
description: 'API generated from RequestHandler with method signature analysis'
},
scopeGroup: 'MyService',
schemas: {
// Define your custom schemas
User: {
type: 'object',
properties: {
id: { type: 'integer' },
username: { type: 'string' },
email: { type: 'string', format: 'email' }
},
required: ['id', 'username', 'email']
}
}
});
// Generate comprehensive OpenAPI specification
await generator.generateFromRequestHandlerAndSave(requestHandler, 'openapi.json');CLI Usage
V2 - TypeScript Compiler API (Recommended)
# Generate from RequestHandler with TypeScript analysis
npx generate-openapi-v2 --request-handler ./src/RequestHandler.ts --output ./openapi.json
# With custom project path
npx generate-openapi-v2 --request-handler ./src/RequestHandler.ts --output ./openapi.json --project-path ./src
# With configuration file
npx generate-openapi-v2 --request-handler ./src/RequestHandler.ts --output ./openapi.json --config ./config.json
# Show help
npx generate-openapi-v2 --helpV1 - Legacy CLI
# Generate with configuration file
generate-openapi --config config.json --output openapi.json
# Generate with endpoints file
generate-openapi --endpoints endpoints.json --output openapi.json
# Generate with both config and endpoints
generate-openapi --config config.json --endpoints endpoints.json
# Show help
generate-openapi --helpPackage.json Script
{
"scripts": {
"generate-openapi": "generate-openapi --config config.json --output openapi.json"
}
}Configuration
The configuration is optional. If you don't provide any configuration, the library will use sensible defaults:
Default Configuration
When no configuration is provided, the library uses these defaults:
{
info: {
title: 'API',
version: '1.0.0',
description: 'Generated API specification'
},
servers: [
{
url: 'http://localhost:3000',
description: 'Development server'
}
],
scopeGroup: 'default',
securitySchemes: {
default: {
type: 'oauth2',
flows: {
clientCredentials: {
tokenUrl: '/oauth2/token'
}
}
}
},
tags: [],
schemas: {},
customGenerators: {}
}Generator Configuration
interface OpenApiGeneratorConfig {
info: {
title: string;
version: string;
description?: string;
contact?: {
name?: string;
email?: string;
url?: string;
};
license?: {
name: string;
url?: string;
};
};
servers?: Array<{
url: string;
description?: string;
}>;
scopeGroup?: string;
defaultSecurityScheme?: string;
securitySchemes?: Record<string, any>;
tags?: Array<{
name: string;
description?: string;
}>;
schemas?: Record<string, any>;
customGenerators?: {
scopeName?: (method: string, path: string, config?: any) => string;
operationId?: (method: string, path: string, config?: any) => string;
summary?: (method: string, path: string, config?: any) => string;
description?: (method: string, path: string, config?: any) => string;
tags?: (method: string, path: string, config?: any) => string[];
};
}Endpoint Configuration
interface ApiEndpoint {
uri: string; // e.g., "get:/api/v1/users"
handler: any; // Handler function or name
scopeName?: string; // Custom scope name
scopeGroup?: string; // Custom scope group
summary?: string; // Custom summary
description?: string; // Custom description
tags?: string[]; // Custom tags
parameters?: EndpointParameter[];
requestBody?: EndpointRequestBody;
responses?: EndpointResponses;
security?: EndpointSecurity[];
deprecated?: boolean;
}Examples
Minimal Example (No Configuration)
import { OpenApiGenerator } from 'common-openapi';
// Create generator with no configuration
const generator = new OpenApiGenerator();
// Add endpoints
generator.addEndpoints([
{
uri: 'get:/api/v1/users',
handler: 'getUsers'
},
{
uri: 'post:/api/v1/users',
handler: 'createUser'
}
]);
// Generate OpenAPI specification
await generator.generateAndSave('openapi.json');Example Configuration File
{
"info": {
"title": "Favourist Manager API",
"version": "1.0.0",
"description": "API for managing user favourites",
"contact": {
"name": "API Support",
"email": "[email protected]"
}
},
"servers": [
{
"url": "http://localhost:3000",
"description": "Development server"
}
],
"scopeGroup": "FavouristManager",
"securitySchemes": {
"default": {
"type": "oauth2",
"flows": {
"clientCredentials": {
"tokenUrl": "/oauth2/token"
}
}
}
},
"tags": [
{
"name": "Favourites",
"description": "Favourite management operations"
}
]
}Example Endpoints File
[
{
"uri": "get:/api/v1/favourites",
"handler": "getFavourites",
"summary": "Get all favourites",
"tags": ["Favourites"]
},
{
"uri": "post:/api/v1/favourites",
"handler": "createFavourite",
"summary": "Create a new favourite",
"tags": ["Favourites"]
},
{
"uri": "get:/api/v1/favourites/:id",
"handler": "getFavouriteById",
"summary": "Get favourite by ID",
"tags": ["Favourites"]
}
]API Reference
OpenApiGenerator
Constructor
constructor(config: OpenApiGeneratorConfig)Methods
addEndpoints(endpoints: ApiEndpoint[]): void- Add multiple endpointsaddEndpoint(endpoint: ApiEndpoint): void- Add a single endpointclearEndpoints(): void- Clear all endpointsgenerateOpenApiSpec(): OpenApiSpec- Generate OpenAPI specificationgenerateAndSave(outputPath: string): Promise<void>- Generate and save to filegetConfig(): OpenApiGeneratorConfig- Get current configurationupdateConfig(newConfig: Partial<OpenApiGeneratorConfig>): void- Update configurationgetEndpoints(): ApiEndpoint[]- Get current endpoints
Utilities
EndpointParser
parseUri(uri: string): ParsedEndpoint- Parse endpoint URIgenerateScopeName(method: string, path: string, scopeGroup?: string): string- Generate scope namegenerateOperationId(method: string, path: string): string- Generate operation IDgenerateSummary(method: string, path: string): string- Generate summarygenerateDescription(method: string, path: string, serviceName?: string): string- Generate descriptiongenerateTags(path: string): string[]- Generate tags
SchemaGenerator
generateErrorResponseSchema(): OpenApiSchema- Generate error response schemagenerateHealthCheckSchema(): OpenApiSchema- Generate health check schemageneratePaginationSchema(): OpenApiSchema- Generate pagination schemagenerateResourceSchema(resourceName: string, properties: Record<string, any>): OpenApiSchema- Generate resource schemagenerateArrayResponseSchema(itemSchema: OpenApiSchema | string): OpenApiSchema- Generate array response schemageneratePaginatedResponseSchema(itemSchema: OpenApiSchema | string): OpenApiSchema- Generate paginated response schema
Advanced Usage
Custom Generators
const generator = new OpenApiGenerator({
// ... other config
customGenerators: {
scopeName: (method, path, config) => {
return `${config.scopeGroup}${method}${path.split('/').pop()}`;
},
operationId: (method, path) => {
return `${method}_${path.replace(/\//g, '_')}`;
},
summary: (method, path) => {
return `${method.toUpperCase()} ${path}`;
}
}
});Custom Schemas
const generator = new OpenApiGenerator({
// ... other config
schemas: {
CustomUser: {
type: 'object',
properties: {
id: { type: 'integer' },
name: { type: 'string' },
email: { type: 'string', format: 'email' }
},
required: ['id', 'name', 'email']
}
}
});Security Configuration
const generator = new OpenApiGenerator({
// ... other config
securitySchemes: {
oauth2: {
type: 'oauth2',
flows: {
clientCredentials: {
tokenUrl: '/oauth2/token',
scopes: {
'read:users': 'Read user information',
'write:users': 'Write user information'
}
}
}
},
apiKey: {
type: 'apiKey',
name: 'X-API-Key',
in: 'header'
}
}
});Integration with Build Process
Using with TypeScript
// scripts/generate-openapi.ts
import 'reflect-metadata';
import { configureContainer } from '../src/config/container';
import { Container } from 'typedi';
import { configureLogger, logger } from 'common-model';
import { OpenApiGenerator } from 'common-openapi';
import RequestHandler from '../src/consumers/RequestHandler';
async function generateOpenApi() {
try {
// Configure container and logger
configureLogger(config.logger.config);
configureContainer();
// Get RequestHandler and endpoints
const requestHandler = Container.get(RequestHandler);
const endpoints = requestHandler.matchingList();
// Create generator
const generator = new OpenApiGenerator({
info: {
title: 'My API',
version: '1.0.0',
description: 'My awesome API'
},
scopeGroup: 'MyService'
});
// Add endpoints and generate
generator.addEndpoints(endpoints);
await generator.generateAndSave('openapi.json');
logger.info('OpenAPI specification generated successfully');
} catch (error) {
logger.error('Failed to generate OpenAPI specification:', error);
process.exit(1);
}
}
generateOpenApi();Package.json Scripts
{
"scripts": {
"build": "yarn clean && tsc && tsc-alias && yarn generate-openapi",
"generate-openapi": "npx ts-node -r tsconfig-paths/register scripts/generate-openapi.ts"
}
}Development
Building
# Install dependencies
yarn install
# Build the library
yarn build
# Run tests
yarn test
# Lint code
yarn lint
# Format code
yarn formatProject Structure
src/
├── interfaces/ # TypeScript interfaces
│ ├── OpenApiSpec.ts
│ └── EndpointConfig.ts
├── generators/ # Generation utilities
│ ├── PathGenerator.ts
│ └── SecurityGenerator.ts
├── utils/ # Utility functions
│ ├── EndpointParser.ts
│ └── SchemaGenerator.ts
├── cli/ # CLI interface
│ └── cli.ts
├── OpenApiGenerator.ts # Main generator class
└── index.ts # Main export fileLicense
MIT
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
Support
For support and questions, please contact the development team or create an issue in the repository.
