Skip to content

azeemali2001/azios

Repository files navigation

Aziosxjs

npm version npm downloads npm downloads per week License: MIT TypeScript Node.js PRs Welcome

🚀 Advanced HTTP client with request monitoring, built-in auth, plugins, middleware, and universal runtime support

Aziosxjs is a modern, lightweight, and highly extensible HTTP client for JavaScript/TypeScript applications. Built for production, featuring intelligent request monitoring, native authentication management, and a powerful plugin architecture.


🌟 Why Aziosxjs?

Feature Aziosxjs Axios Fetch
Request Monitoring ✅ Built-in dashboard ❌ 3rd party ❌ No
Auth Manager ✅ Native + auto-refresh ❌ Manual ❌ No
Plugin System ✅ Full lifecycle ❌ No ❌ No
Middleware ✅ Koa-style ❌ No ❌ No
Interceptors ✅ Request/Response ✅ Yes ❌ No
Retry Logic ✅ Exponential backoff ❌ No ❌ No
Caching ✅ TTL-based ❌ No ❌ No
Rate Limiting ✅ Built-in ❌ No ❌ No
TypeScript ✅ Full support ✅ Yes ✅ Partial
Universal Runtime ✅ Node/Browser/Deno ❌ Node/Browser ✅ Universal

🚀 Quick Start

Installation

npm install aziosxjs

Basic Usage

import azios from 'aziosxjs'

// GET request
const user = await azios.get('https://api.example.com/users/1')
console.log(user.data)

// POST request
const post = await azios.post('https://api.example.com/posts', {
  title: 'Hello World',
  body: 'My first post'
})

// PUT request
await azios.put('https://api.example.com/posts/1', {
  title: 'Updated Title'
})

// DELETE request
await azios.delete('https://api.example.com/posts/1')

✨ Key Features

1. 📊 Request Monitoring & Debug Dashboard

Monitor all HTTP requests with real-time debugging:

import azios from 'aziosxjs'

// Enable monitoring
azios.monitor.enable()

// Make requests...
await azios.get('https://api.example.com/users')

// View request history
console.log(azios.monitor.getHistory())

// Get statistics
console.log(azios.monitor.getStats())
// { totalRequests: 5, totalErrors: 1, averageDuration: 245, ... }

// Export for analysis
const json = azios.monitor.exportJSON()
const csv = azios.monitor.exportCSV()

// Filter and analyze
const errors = azios.monitor.getErrors()
const getRequests = azios.monitor.getByMethod('GET')

2. 🔐 Built-in Authentication Manager

Enterprise-grade authentication with automatic token refresh:

import azios, { createAuthPlugin } from 'aziosxjs'

// Setup auth
const authPlugin = createAuthPlugin({
  refreshUrl: 'https://api.example.com/auth/refresh',
  logoutUrl: 'https://api.example.com/auth/logout'
})

await azios.installPlugin(authPlugin)

// Now all requests:
// ✅ Attach Authorization headers
// ✅ Detect 401 responses
// ✅ Refresh token automatically
// ✅ Retry with new token

3. 🔌 Plugin System

Extend functionality with a clean plugin architecture:

import azios, { AziosPlugin } from 'aziosxjs'

const loggingPlugin: AziosPlugin = {
  name: 'logger',
  version: '1.0.0',
  hooks: {
    beforeRequest: (config) => {
      console.log(`📡 ${config.method} ${config.url}`)
      return config
    },
    afterResponse: (response) => {
      console.log(`✅ Status: ${response.status}`)
      return response
    }
  }
}

await azios.installPlugin(loggingPlugin)

4. ⚙️ Middleware Pipeline

Koa-style middleware for request processing:

azios.use(async (ctx, next) => {
  console.log('Before request')
  await next()
  console.log('After response')
})

5. 🔄 Interceptors

Intercept and transform requests/responses:

azios.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `Bearer ${token}`
    return config
  }
)

azios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      // Handle unauthorized
    }
    return Promise.reject(error)
  }
)

6. ⚡ Performance Features

Retry with Exponential Backoff

await azios.get('/api/data', {
  retry: 3,         // Retry 3 times
  retryDelay: 1000  // 1s, 2s, 4s delays
})

Response Caching

await azios.get('/api/users', {
  cache: true,      // Enable caching
  cacheTTL: 60000   // Cache for 60 seconds
})

Rate Limiting

await azios.post('/api/data', payload, {
  rateLimit: 1000   // 1 request per second
})

Request Deduplication

// Both use the same network call
const [data1, data2] = await Promise.all([
  azios.get('/api/users/1'),
  azios.get('/api/users/1')
])

📖 Complete Examples

Example 1: Simple GET/POST

import azios from 'aziosxjs'

async function main() {
  const users = await azios.get('https://jsonplaceholder.typicode.com/users')
  console.log(users.data)

  const post = await azios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'My Post',
    body: 'Content',
    userId: 1
  })
  console.log(post.data)
}

Example 2: With Request Monitoring

azios.monitor.enable()

await azios.get('https://api.example.com/users')
await azios.post('https://api.example.com/data', { /* data */ })

console.log(azios.monitor.getSummary())
console.log(azios.monitor.getStats())

Example 3: With Authentication

const authPlugin = createAuthPlugin({
  refreshUrl: 'https://api.example.com/refresh',
  logoutUrl: 'https://api.example.com/logout'
})

await azios.installPlugin(authPlugin)

// Requests automatically handle auth and token refresh
const data = await azios.get('https://api.example.com/protected')

Example 4: Custom Instances

import { createInstance } from 'aziosxjs'

const api = createInstance({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  headers: {
    'X-Custom-Header': 'value'
  }
})

const data = await api.get('/users')

Example 5: Advanced Configuration

const response = await azios.request({
  url: '/api/users',
  method: 'GET',
  baseURL: 'https://api.example.com',
  headers: { Authorization: 'Bearer token' },
  params: { page: 1, limit: 10 },
  timeout: 5000,
  retry: 2,
  retryDelay: 500,
  cache: true,
  cacheTTL: 30000,
  rateLimit: 1000
})

🔧 Configuration

Request Config API

interface AziosRequestConfig {
  url?: string
  method?: string
  baseURL?: string
  headers?: Record<string, any>
  params?: Record<string, any>
  data?: any
  timeout?: number
  responseType?: string
  signal?: AbortSignal
  retry?: number
  retryDelay?: number
  cache?: boolean
  cacheTTL?: number
  rateLimit?: number
}

📦 TypeScript Support

Full TypeScript support with complete type safety:

import azios, { 
  AziosInstance, 
  AziosRequestConfig, 
  AziosResponse,
  RequestLog,
  TokenConfig
} from 'aziosxjs'

const response: AziosResponse = await azios.get('/api/users')

🌍 Universal Runtime Support

Works across different JavaScript runtimes:

import { detectRuntime, currentRuntime } from 'aziosxjs'

console.log(currentRuntime) // 'node' | 'browser' | 'deno' | 'bun'

Supported: Node.js, Browser, Deno, Bun


🎯 API Reference

Monitoring API

azios.monitor.enable()              // Enable tracking
azios.monitor.disable()             // Disable tracking
azios.monitor.getHistory()          // Get all logs
azios.monitor.getStats()            // Get statistics
azios.monitor.getErrors()           // Get failed requests
azios.monitor.getByMethod(method)   // Filter by HTTP method
azios.monitor.getByUrl(pattern)     // Filter by URL
azios.monitor.exportJSON()          // Export as JSON
azios.monitor.exportCSV()           // Export as CSV
azios.monitor.getSummary()          // Get formatted summary
azios.monitor.clear()               // Clear all logs

Auth Manager API

const auth = new AuthManager()

auth.initialize(endpoints)          // Setup endpoints
auth.setToken(token)                // Store token
auth.getToken()                     // Get stored token
auth.getAccessToken()               // Get access token string
auth.hasToken()                     // Check if token exists
auth.isTokenExpired()               // Check expiration
auth.refreshAccessToken()           // Refresh token
auth.attachAuthHeader(config)       // Add auth header
auth.handle401(config)              // Handle 401 response
auth.logout()                       // Logout and clear
auth.getStatus()                    // Get auth status

🛡️ Best Practices

Security

// ✅ DO: Use secure token storage
const authPlugin = createAuthPlugin({
  refreshUrl: 'https://api.example.com/auth/refresh',
  logoutUrl: 'https://api.example.com/auth/logout'
})

// ❌ DON'T: Store tokens in localStorage
// localStorage.setItem('token', sensitiveToken)

Error Handling

import { AziosError } from 'aziosxjs'

try {
  await azios.get('/api/users')
} catch (error) {
  if (error instanceof AziosError) {
    console.log(`[${error.response?.status}] ${error.message}`)
  }
}

Production Monitoring

if (process.env.NODE_ENV === 'development') {
  azios.monitor.enable()
}

setInterval(() => {
  const stats = azios.monitor.getStats()
  if (stats.totalErrors > 10) {
    alerting.warn('High error rate!')
  }
}, 60000)

🧪 Testing

npm test                      # Run all tests
npm run test:sprint8:monitoring  # Test monitoring
npm run test:sprint8:auth        # Test auth

📚 Documentation


🤝 Contributing

Contributions welcome! Please see CONTRIBUTING.md


📄 License

MIT © 2024 Azeem Ali


🙋 Support

Made with ❤️ for the JavaScript community

About

Aziosxjs — A modular HTTP client for Node.js with retries, caching, deduplication and rate limiting.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors