npm package: @linxs/amors
Description: Amors is a minimalist request tool library
Author: Lin.xs
Latest version: 0.4.0

# @linxs/amors

A lightweight, promise-based HTTP client for the browser and Node.js with interceptors, caching, and request/response transformation.

中文文档：[API Reference](./README-Zh.md)

## Features

- 🚀 Promise-based HTTP client for browser and Node.js
- 🔄 Request and response interceptors with proper body consumption handling
- 💾 Built-in request caching with LRU strategy
- ⏱️ Advanced timeout handling with AbortController support
- 🛠️ Extensible configuration
- 📦 Full TypeScript support with strict type safety
- 🔄 Automatic request/response transformation
- 🛡️ Safe Response body consumption - prevents "body stream already read" errors
- ⚡ Optimized queue management for concurrent requests
- 🔌 Pluggable adapter architecture

## Installation

```bash
# Using npm
npm install @linxs/amors

# Using yarn
yarn add @linxs/amors

# Using pnpm
pnpm add @linxs/amors
```

## Quick Start

### Basic Amors Usage

```typescript
import { Amors } from '@linxs/amors';

// Create an instance
const api = new Amors({
  baseURL: 'https://api.example.com',
  prefix: '/v1',
  timeout: 30000 // 30 seconds
});

// Make requests
const response = await api.get('/users');
const data = await response.json();

// POST request with data
// Body objects are automatically JSON.stringify'd
// Content-Type defaults to 'application/json'
const newUser = await api.post('/users', {
  body: { name: 'John Doe' }
});
```

### Adapter Usage

```typescript
import { AmorsAdapter } from '@linxs/amors';
import { Amors } from '@linxs/amors/fetch';

// Create an adapter with queue and cache support
const adapter = new AmorsAdapter({
  adapter: Amors,
  config: {
    baseURL: 'https://api.example.com',
    timeout: 30000
  },
  cache: {
    capacity: 100,
    ttl: 5 * 60 * 1000 // 5 minutes
  },
  queue: {
    global: true,
    concurrent: 3
  }
});

// Use the adapter
const response = await adapter.get('/users');

// Use queue
const queue = adapter.queue();
const queuedResponse = await queue.get('/data');
```

### Interceptors

Safe Response body consumption without "body stream already read" errors:

```typescript
const api = new Amors({
  baseURL: 'https://api.example.com',
  interceptors: {
    request: (config) => {
      // Add auth token
      const token = localStorage.getItem('token');
      if (token) {
        config.headers = {
          ...config.headers,
          'Authorization': `Bearer ${token}`
        };
      }
      return config;
    },
    response: async (response) => {
      // Safe to consume response body in interceptors
      const data = await response.json();
      console.log('Response received:', data);
      
      // Return response (Amors handles cloning automatically)
      return response;
    }
  }
});

// User can still access response body even though interceptor consumed it
const response = await api.get('/users');
const userData = await response.json(); // ✅ Works perfectly!
```

### Caching

```typescript
const api = new Amors({
  cache: {
    capacity: 50,
    ttl: 5 * 60 * 1000 // 5 minutes
  }
});

// First request - fetches from network
const data1 = await api.get('/data');

// Subsequent request - returns from cache
const data2 = await api.get('/data');

// Force update from network
const freshData = await api.get('/data', {}, {
  cache: { forceUpdate: true }
});
```

### Error Handling

```typescript
try {
  const response = await api.get('/users/123');
  // Handle success
} catch (error) {
  if (error.name === 'TimeoutError') {
    console.log('Request timed out');
  } else if (error.name === 'AbortError') {
    console.log('Request was aborted');
  } else if (error.response) {
    console.log('HTTP Error:', error.response.status);
  } else {
    console.log('Network Error:', error.message);
  }
}
```

## Architecture

Amors provides two main components:

1. **Amors**: Core HTTP client with fetch-based implementation
2. **AmorsAdapter**: Pluggable adapter with queue management and enhanced caching

## API Overview

### Core Methods

- `get(url, config?, options?)` - GET request
- `post(url, config?, options?)` - POST request  
- `put(url, config?, options?)` - PUT request
- `delete(url, config?, options?)` - DELETE request
- `patch(url, config?, options?)` - PATCH request
- `head(url, config?, options?)` - HEAD request
- `options(url, config?, options?)` - OPTIONS request

### Configuration Options

- `baseURL` - Base URL for all requests
- `prefix` - URL prefix to append to baseURL
- `timeout` - Request timeout in milliseconds
- `cache` - Cache configuration with capacity and TTL
- `interceptors` - Request and response interceptors
- `queue` - Queue configuration for concurrent request management

## Documentation

For detailed documentation and advanced usage:

- [Amors Documentation](./docs/Amors.md) - Core HTTP client guide
- [AmorsAdapter Documentation](./docs/AmorsAdapter.md) - Adapter and queue management
- [API Reference](./docs/Amors.md#api-reference) - Complete API documentation

## Browser Support

Amors supports all modern browsers and Node.js 16+. For older browsers, you may need polyfills for:

- Promise
- Fetch API
- Object.entries
- AbortController

## TypeScript

Fully typed with TypeScript. All types are exported for your convenience:

```typescript
import type { 
  AmorsRequestInit, 
  AmorsRequestOptions,
  AmorsConfigInit 
} from '@linxs/amors';
```

## Contributing

1. Fork it!
2. Create your feature branch: `git checkout -b feature/my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin feature/my-new-feature`
5. Submit a pull request

## License

MIT

---

## Why Amors?

Amors solves common pain points in HTTP client libraries:

- **Response Body Consumption**: Automatically handles response cloning to prevent "body stream already read" errors
- **Type Safety**: Full TypeScript support with strict typing
- **Performance**: Built-in caching and queue management for optimal performance
- **Flexibility**: Pluggable adapter architecture for different use cases
- **Developer Experience**: Clean API with comprehensive error handling

Perfect for applications that need reliable HTTP communication with advanced features like request queuing, response caching, and safe interceptor handling.