@diagramers/api
TypeScript icon, indicating that this package has built-in type declarations

4.0.14 • Public • Published

@diagramers/api

A comprehensive Node.js API template with TypeScript, Firebase Functions, Socket.io, and extensive authentication and communication capabilities.

🚀 Features

Core Framework

  • TypeScript - Full TypeScript support with strict typing
  • Express.js - Fast, unopinionated web framework
  • MongoDB - NoSQL database with Mongoose ODM
  • Firebase Functions - Serverless deployment support
  • Socket.io - Real-time bidirectional communication
  • Webpack - Module bundling and optimization

Authentication & Authorization

  • Multi-Provider Authentication:
    • Internal (Database-based) authentication
    • Firebase Authentication
    • OAuth providers (Google, GitHub, Facebook, Twitter, LinkedIn, Microsoft, Apple, Discord, Spotify, Twitch)
    • SMS authentication (Twilio, AWS SNS, Vonage, MessageBird)
    • Email authentication (Nodemailer, SendGrid, AWS SES, Mailgun, Postmark)
    • LDAP authentication
    • SAML authentication
    • OAuth2 generic provider
    • OpenID Connect
    • WebAuthn (FIDO2) authentication
    • Social media authentication (Instagram, TikTok, Snapchat, Pinterest, Reddit, Slack, Zoom, Dropbox, Bitbucket, GitLab)

Security Features

  • JWT Tokens - JSON Web Token authentication
  • Password Policies - Configurable password requirements
  • Rate Limiting - Request throttling and protection
  • CORS - Cross-Origin Resource Sharing configuration
  • Security Headers - Helmet.js security middleware
  • Session Management - Secure session handling
  • Multi-factor Authentication - Enhanced security options

Communication Services

  • Email System:

    • Multiple email providers (SMTP, SendGrid, AWS SES, Mailgun, Postmark)
    • Template engine support (Handlebars)
    • Email verification, password reset, login codes
    • Custom email providers
  • SMS System:

    • Multiple SMS providers (Twilio, AWS SNS, Vonage, MessageBird)
    • SMS verification codes
    • Custom SMS providers
  • Push Notifications:

    • Firebase Cloud Messaging (FCM)
    • Cross-platform push notifications

Database & Storage

  • MongoDB Integration - Native MongoDB support with connection pooling
  • Database Seeding - Automated data seeding and management
  • File Storage:
    • Local file storage
    • AWS S3 integration
    • Google Cloud Storage
    • Cloudinary integration

Development & DevOps

  • CLI Tools - Command-line interface for development
  • Module Generation - Automated module scaffolding
  • Endpoint Generation - Quick API endpoint creation
  • Database Migration - Schema migration tools
  • Backup & Restore - Database backup automation
  • Health Checks - Application monitoring endpoints
  • Logging - Comprehensive logging system (JSON, colored, file-based)
  • External Logging - Sentry, Loggly, Papertrail integration

Performance & Monitoring

  • Performance Monitoring - Application performance tracking
  • New Relic Integration - APM monitoring
  • Metrics Collection - Application metrics
  • Compression - Response compression
  • Caching - Redis integration for caching

Third-Party Integrations

  • Payment Processing:

    • Stripe integration
    • PayPal integration
  • Analytics:

    • Google Analytics integration

Development Tools

  • Hot Reload - Development server with auto-reload
  • Type Checking - TypeScript type validation
  • Linting - ESLint code quality checks
  • Formatting - Prettier code formatting
  • Documentation - Auto-generated API documentation
  • Testing - Test database configuration

📦 Installation

npm install @diagramers/api

🛠️ Quick Start

1. Initialize a New API Project

npx diagramers-cli api init my-api-project
cd my-api-project

2. Configure Environment Variables

cp .env.example .env
# Edit .env with your configuration

3. Install Dependencies

npm install --legacy-peer-deps

4. Start Development Server

npm run dev

🔧 Configuration

Environment Variables

The API supports extensive configuration through environment variables:

Basic Configuration

NODE_ENV=development
PORT=3000
HOST=localhost
APP_URL=http://localhost:3000

Database Configuration

DATABASE_TYPE=mongodb
DATABASE_URL=mongodb://localhost:27017/diagramers
DATABASE_NAME=diagramers

Authentication Configuration

JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=1h
AUTH_DEFAULT_PROVIDER=internal

Email Configuration

EMAIL_ENABLED=true
EMAIL_PROVIDER=nodemailer
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password

SMS Configuration

SMS_ENABLED=false
SMS_PROVIDER=twilio
TWILIO_ACCOUNT_SID=your-twilio-account-sid
TWILIO_AUTH_TOKEN=your-twilio-auth-token
TWILIO_PHONE_NUMBER=+1234567890

📚 API Documentation

Authentication Endpoints

Internal Authentication

  • POST /api/auth/register - User registration
  • POST /api/auth/login - User login
  • POST /api/auth/logout - User logout
  • POST /api/auth/refresh - Refresh JWT token
  • POST /api/auth/forgot-password - Password reset request
  • POST /api/auth/reset-password - Password reset

OAuth Authentication

  • GET /api/auth/oauth/:provider - OAuth provider authentication
  • GET /api/auth/oauth/:provider/callback - OAuth callback

SMS Authentication

  • POST /api/auth/sms/send-code - Send SMS verification code
  • POST /api/auth/sms/verify-code - Verify SMS code

Email Authentication

  • POST /api/auth/email/send-code - Send email verification code
  • POST /api/auth/email/verify-code - Verify email code

User Management

  • GET /api/users - Get all users
  • GET /api/users/:id - Get user by ID
  • PUT /api/users/:id - Update user
  • DELETE /api/users/:id - Delete user

Email Management

  • GET /api/email/configs - Get email configurations
  • POST /api/email/configs - Create email configuration
  • PUT /api/email/configs/:id - Update email configuration
  • DELETE /api/email/configs/:id - Delete email configuration
  • POST /api/email/send - Send email

Notifications

  • GET /api/notifications - Get notifications
  • POST /api/notifications - Create notification
  • PUT /api/notifications/:id - Update notification
  • DELETE /api/notifications/:id - Delete notification

🛠️ Development Commands

Basic Commands

npm run dev          # Start development server
npm run build        # Build for production
npm run start        # Start production server
npm run clean        # Clean build artifacts

Database Commands

npm run seed         # Seed database
npm run seed:force   # Force seed database
npm run seed:reset   # Reset and seed database
npm run seed:truncate # Truncate database

Generation Commands

npm run generate:module    # Generate new module
npm run generate:endpoint  # Generate new endpoint
npm run generate:table     # Generate database table
npm run generate:relation  # Generate database relation

Code Quality Commands

npm run lint         # Run ESLint
npm run lint:fix     # Fix ESLint issues
npm run type-check   # TypeScript type checking
npm run format       # Format code with Prettier
npm run format:check # Check code formatting

Documentation Commands

npm run docs         # Generate documentation
npm run docs:serve   # Serve documentation

Docker Commands

npm run docker:build     # Build Docker image
npm run docker:run       # Run Docker container
npm run docker:compose   # Start with Docker Compose
npm run docker:compose:down # Stop Docker Compose

Maintenance Commands

npm run backup           # Backup database
npm run backup:restore   # Restore database backup
npm run migrate          # Run database migrations
npm run migrate:create   # Create new migration
npm run migrate:rollback # Rollback migration

Monitoring Commands

npm run health       # Health check
npm run logs         # View application logs
npm run logs:clear   # Clear application logs
npm run monitor      # Start monitoring

🔌 Plugin System

The API supports a plugin system for extending functionality:

Plugin Structure

src/plugins/
├── base/
│   ├── manager.ts
│   └── plugin.ts
└── registry/
    └── auth.plugin.ts

Creating Custom Plugins

import { BasePlugin } from '../base/plugin';

export class CustomPlugin extends BasePlugin {
  async initialize(): Promise<void> {
    // Plugin initialization logic
  }

  async execute(data: any): Promise<any> {
    // Plugin execution logic
  }
}

🧪 Testing

Test Configuration

TEST_DATABASE_URL=mongodb://localhost:27017/diagramers-api-test
TEST_JWT_SECRET=test-jwt-secret

Running Tests

npm test              # Run all tests
npm run test:unit     # Run unit tests
npm run test:integration # Run integration tests
npm run test:coverage # Run tests with coverage

🚀 Deployment

Firebase Functions Deployment

npm run deploy              # Deploy to Firebase Functions
npm run deploy:staging      # Deploy to staging
npm run deploy:production   # Deploy to production

Docker Deployment

npm run docker:build
npm run docker:run

Environment-Specific Deployment

npm run deploy:staging      # Deploy to staging environment
npm run deploy:production   # Deploy to production environment

📊 Monitoring & Logging

Logging Configuration

LOG_LEVEL=info
LOG_FORMAT=colored
LOG_FILE_ENABLED=true
LOG_FILE_PATH=logs/app.log

External Logging Services

  • Sentry - Error tracking and monitoring
  • Loggly - Log aggregation and analysis
  • Papertrail - Log management and search

Health Checks

curl http://localhost:3000/health

🔒 Security

Security Headers

  • Helmet.js for security headers
  • CORS configuration
  • Rate limiting
  • Input validation

Authentication Security

  • JWT token management
  • Password hashing with bcrypt
  • Session management
  • Multi-factor authentication

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

📄 License

MIT License - see LICENSE file for details

🔗 Related Packages

📞 Support

For support and questions:

  • Create an issue on GitHub
  • Check the documentation
  • Review the examples in the codebase

🗺️ Roadmap

  • [ ] GraphQL support
  • [ ] Microservices architecture
  • [ ] Kubernetes deployment
  • [ ] Advanced caching strategies
  • [ ] Real-time analytics
  • [ ] Advanced security features
  • [ ] Multi-tenant support
  • [ ] API versioning
  • [ ] Advanced rate limiting
  • [ ] Webhook system

Package Sidebar

Install

npm i @diagramers/api

Weekly Downloads

1,145

Version

4.0.14

License

MIT

Unpacked Size

939 kB

Total Files

79

Last publish

Collaborators

  • aydahab