UNPKG

api-docs-automation

Version:

Automated API documentation generator that parses JSDoc comments and stores documentation in MongoDB

410 lines (315 loc) • 11.7 kB
# API Docs Generator šŸš€ **Automated API documentation generator that parses JSDoc comments and stores documentation in MongoDB** A powerful Node.js package that automatically generates comprehensive API documentation from your Express.js route files by parsing JSDoc comments. Perfect for teams that want to maintain up-to-date API documentation without manual effort. ## ✨ Features - **šŸ” Automatic Parsing**: Scans your route files and extracts API documentation from JSDoc comments - **šŸ“Š MongoDB Storage**: Stores structured documentation with full metadata and versioning - **šŸ”„ Smart Updates**: Only updates documentation when changes are detected - **🌳 Nested Routes**: Supports complex directory structures and nested route files - **šŸ“ˆ Analytics**: Built-in usage analytics and performance metrics - **šŸ“¤ Multiple Exports**: Export to OpenAPI/Swagger, Postman, and Insomnia formats - **šŸ” Search & Filter**: Powerful search and filtering capabilities - **šŸ·ļø Tagging System**: Organize APIs with custom tags and categories - **šŸ“± REST API**: Full REST API for accessing and managing documentation - **⚔ CLI Tool**: Command-line interface for easy integration ## šŸš€ Quick Start ### Installation ```bash # Install globally npm install -g api-docs-automation # Or install locally in your project npm install api-docs-automation ``` ### Basic Usage 1. **Add JSDoc comments to your routes:** ```javascript /** * @route GET /api/users * @desc Get all users * @access Public * @version v1 * @tags users,crud * @response 200 {status: "success", data: [{id, name, email}], message: string} * @response 500 {status: "error", message: string} */ router.get('/', userController.getAllUsers); /** * @route POST /api/users * @desc Create a new user * @access Public * @version v1 * @tags users,crud * @requestBody {"name": "string", "email": "string", "password": "string"} * @response 201 {status: "success", data: {id, name, email}, message: string} * @response 400 {status: "error", message: "Validation error"} */ router.post('/', userController.createUser); ``` 2. **Generate documentation:** ```bash # Using the CLI tool api-docs-automation # Or with custom options api-docs-automation --routes-dir ./src/routes --mongo-uri mongodb://localhost:27017/my-api-docs --verbose ``` 3. **Access your documentation:** - **Web Interface**: `http://localhost:3000/api/docs` - **OpenAPI Spec**: `http://localhost:3000/api/docs/export/openapi` - **Postman Collection**: `http://localhost:3000/api/docs/export/postman` ## šŸš€ How to Use Published Package ### Option 1: Use npx (no installation needed) ```bash npx api-docs-automation --mongo-uri mongodb://localhost:27017/my-api-docs ``` ### Option 2: Install globally ```bash npm install -g api-docs-automation api-docs-automation --mongo-uri mongodb://localhost:27017/my-api-docs ``` ### Option 3: Use in your project ```bash npm install api-docs-automation npx api-docs-automation --mongo-uri mongodb://localhost:27017/my-api-docs ``` ### Available CLI Options - `--routes-dir <path>` - Custom routes directory (default: `./routes`) - `--mongo-uri <uri>` - MongoDB connection string - `--verbose` - Enable detailed logging - `--help` - Show help - `--version` - Show version ## šŸ“‹ JSDoc Format ### Required Tags - `@route` - HTTP method and path (e.g., `GET /api/users`) - `@desc` - API description ### Optional Tags - `@access` - Access level (e.g., `Public`, `Private`, `Admin`) - `@version` - API version (e.g., `v1`, `v2`) - `@tags` - Comma-separated tags (e.g., `users,crud,auth`) - `@requestBody` - JSON schema for request body - `@response` - Response examples with status codes - `@param` - URL parameters (e.g., `id string required User ID`) - `@example` - Usage examples - `@deprecated` - Mark as deprecated - `@migrated_from` - Previous endpoint path ### Example ```javascript /** * @route GET /api/users/:id * @desc Get a single user by ID * @access Public * @version v1 * @tags users,crud * @param id string required The user ID * @response 200 {status: "success", data: {id, name, email}, message: string} * @response 404 {status: "error", message: "User not found"} * @response 400 {status: "error", message: "Invalid user ID"} */ router.get('/:id', userController.getUserById); ``` ## šŸ› ļø Configuration ### Environment Variables ```bash # MongoDB connection MONGODB_URI=mongodb://localhost:27017/api-docs # Server configuration PORT=3000 NODE_ENV=development ``` ### CLI Options ```bash api-docs-generator [options] Options: --routes-dir <path> Directory containing route files (default: ./routes) --mongo-uri <uri> MongoDB connection string (default: mongodb://localhost:27017/api-docs) --verbose Enable verbose logging --help Show this help message --version Show version ``` ## šŸ“š API Endpoints ### Documentation Management - `GET /api/docs` - Get all API documentation with filtering - `GET /api/docs/:id` - Get specific API documentation - `GET /api/docs/:method/:path` - Get API by method and path - `GET /api/docs/stats` - Get documentation statistics - `GET /api/docs/search?q=<query>` - Search documentation ### Export Options - `GET /api/docs/export/openapi` - Export as OpenAPI/Swagger spec - `GET /api/docs/export/postman` - Export as Postman collection - `GET /api/docs/export/insomnia` - Export as Insomnia collection ### Analytics - `GET /api/docs/analytics/usage` - Get usage analytics - `GET /api/docs/analytics/performance` - Get performance metrics ### Management - `PATCH /api/docs/:id/deprecate` - Mark API as deprecated - `DELETE /api/docs/cleanup` - Clean up deprecated APIs - `POST /api/docs/validate` - Validate documentation format - `GET /api/docs/schema` - Get documentation schema - `GET /api/docs/health` - Check system health ## šŸ”§ Integration ### Programmatic Usage ```javascript const { parseRoutesAndUpdateDocs } = require('api-docs-generator'); // Generate documentation const results = await parseRoutesAndUpdateDocs({ routesDir: './routes', mongoUri: 'mongodb://localhost:27017/api-docs', verbose: true }); console.log(`Processed ${results.apisProcessed} APIs`); ``` ### GitHub Actions Integration ```yaml name: Generate API Documentation on: push: branches: [main, dev] paths: ['routes/**', 'controllers/**'] jobs: generate-docs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '18' - run: npm install -g api-docs-generator - run: api-docs-generator --verbose - run: | git config --local user.email "action@github.com" git config --local user.name "GitHub Action" git add . git commit -m "šŸ¤– Auto-update API documentation" || exit 0 git push ``` ### Express.js Integration ```javascript const express = require('express'); const { createServer, createRoutes } = require('api-docs-generator'); const app = express(); // Add API documentation routes app.use('/api/docs', createRoutes()); // Start server const server = createServer({ port: process.env.PORT || 3000, mongoUri: process.env.MONGODB_URI }); server.start(); ``` ## šŸ“Š Database Schema The package creates an `ApiDoc` collection with the following structure: ```javascript { method: "GET", // HTTP method path: "/api/users", // API path description: "Get all users", // API description access: "Public", // Access level version: "v1", // API version tags: ["users", "crud"], // Tags requestBody: {}, // Request body schema responses: { // Response examples "200": { status: "success" }, "400": { status: "error" } }, parameters: [], // URL parameters examples: [], // Usage examples sourceFile: "routes/users.js", // Source file lastUpdated: Date, // Last update timestamp isActive: true, // Active status deprecated: false, // Deprecated status deprecatedReason: "", // Deprecation reason migratedFrom: "" // Previous endpoint } ``` ## šŸŽÆ Use Cases ### For Development Teams - **Automated Documentation**: No more manual API documentation updates - **Consistent Format**: Standardized JSDoc format across the team - **Version Control**: Track API changes and deprecations - **Team Collaboration**: Shared documentation accessible to all team members ### For API Consumers - **Interactive Documentation**: Explore APIs with real examples - **Multiple Formats**: Export to your preferred tool (Postman, Insomnia, etc.) - **Search & Filter**: Find APIs quickly with powerful search - **Always Up-to-Date**: Documentation automatically syncs with code changes ### For DevOps - **CI/CD Integration**: Automate documentation generation in pipelines - **Monitoring**: Track API usage and performance - **Health Checks**: Monitor documentation system health - **Backup & Recovery**: MongoDB provides reliable data storage ## šŸ” Advanced Features ### Custom Tags Create custom JSDoc tags for your specific needs: ```javascript /** * @route POST /api/payments * @desc Process payment * @access Private * @version v1 * @tags payments,financial * @rate_limit 100/hour * @audit_log true * @encryption required */ router.post('/', paymentController.processPayment); ``` ### Bulk Operations ```javascript // Import multiple APIs at once const { parseRoutesAndUpdateDocs } = require('api-docs-generator'); await parseRoutesAndUpdateDocs({ routesDir: './routes', mongoUri: 'mongodb://localhost:27017/api-docs', verbose: true }); ``` ### Custom Export Formats ```javascript // Export to custom format const { exportCustomFormat } = require('api-docs-generator'); const customFormat = await exportCustomFormat({ format: 'raml', includeExamples: true, includeSchemas: true }); ``` ## šŸš€ Getting Started 1. **Install the package:** ```bash npm install -g api-docs-generator ``` 2. **Add JSDoc comments to your routes:** ```javascript /** * @route GET /api/health * @desc Health check endpoint * @access Public * @version v1 * @tags health * @response 200 {status: "success", message: "Service is healthy"} */ router.get('/health', (req, res) => { res.json({ status: 'success', message: 'Service is healthy' }); }); ``` 3. **Generate documentation:** ```bash api-docs-generator --verbose ``` 4. **Access your documentation:** - Web: `http://localhost:3000/api/docs` - API: `http://localhost:3000/api/docs/export/openapi` ## šŸ¤ Contributing We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details. ## šŸ“„ License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## šŸ†˜ Support - **Documentation**: [GitHub Wiki](https://github.com/your-username/api-docs-generator/wiki) - **Issues**: [GitHub Issues](https://github.com/your-username/api-docs-generator/issues) - **Discussions**: [GitHub Discussions](https://github.com/your-username/api-docs-generator/discussions) ## šŸ™ Acknowledgments - Built with [Express.js](https://expressjs.com/) - Database powered by [MongoDB](https://www.mongodb.com/) - JSDoc parsing with [comment-parser](https://github.com/yavorskiy/comment-parser) - OpenAPI support for industry-standard documentation --- **Made with ā¤ļø for the developer community**