@tomei/general
v0.23.1
Published
Tomei general object package
Downloads
439
Readme
@tomei/general
A TypeScript package containing general utilities and classes for Tomei applications, including a robust API client with automatic retry logic and failure tracking.
Installation
npm install @tomei/generalQuick Start
- Initialize Database Connection (in your
main.tsorapp.js):
import { GeneralDB } from '@tomei/general';
await GeneralDb.init({
dialect: 'mysql',
host: process.env.DB_HOST,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
- Use ApiClient anywhere in your application:
import { ApiClient } from '@tomei/general';
const apiClient = new ApiClient({
config: { baseURL: 'https://api.example.com' }
});
const response = await apiClient.get('/users');API Client
The ApiClient class provides a robust HTTP client with automatic retry logic and failure tracking capabilities.
Features
- Automatic Retry Logic: Retries failed requests with exponential backoff
- Failure Tracking: Automatically logs failed requests to database for debugging
- TypeScript Support: Full TypeScript support with generic types
- Axios-based: Built on top of Axios for reliability and flexibility
- HTTP Methods: Supports GET, POST, PUT, DELETE, and PATCH operations
Basic Usage
import { ApiClient, IApiClientRequestConfig } from '@tomei/general';
// Create API client instance with base configuration
const apiClient = new ApiClient({
retryCount: 3, // Optional: defaults to 3
config: { // Optional: base Axios configuration
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json'
}
}
});
// Make HTTP requests
try {
const response = await apiClient.get('/users');
console.log(response.data);
} catch (error) {
console.error('API request failed:', error);
}
// With database transaction
const config: IApiClientRequestConfig = {
headers: { 'Authorization': 'Bearer token' },
dbTransaction: myTransaction
};
const response = await apiClient.get('/users', config);Configuration Options
ApiClientOptions
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| retryCount | number | 3 | Number of retry attempts for failed requests |
| config | AxiosRequestConfig | undefined | Base Axios configuration (baseURL, timeout, headers, etc.) |
HTTP Methods
The API client provides convenient methods for common HTTP operations. All methods accept an optional IApiClientRequestConfig parameter that extends AxiosRequestConfig with an additional dbTransaction property for database transaction handling.
GET Request
const response = await apiClient.get<User[]>('/api/users');
const users = response.data;
// With custom config and database transaction
const config: IApiClientRequestConfig = {
headers: { 'Authorization': 'Bearer token' },
dbTransaction: myTransaction
};
const response = await apiClient.get<User[]>('/api/users', config);POST Request
const newUser = { name: 'John Doe', email: '[email protected]' };
const response = await apiClient.post<User>('/api/users', newUser);
const createdUser = response.data;
// With database transaction
const response = await apiClient.post<User>('/api/users', newUser, {
dbTransaction: myTransaction
});PUT Request
const updatedUser = { id: 1, name: 'Jane Doe', email: '[email protected]' };
const response = await apiClient.put<User>('/api/users/1', updatedUser);
// With database transaction
const response = await apiClient.put<User>('/api/users/1', updatedUser, {
dbTransaction: myTransaction
});DELETE Request
await apiClient.delete('/api/users/1');
// With database transaction
await apiClient.delete('/api/users/1', {
dbTransaction: myTransaction
});
#### PATCH Request
```typescript
const partialUpdate = { email: '[email protected]' };
const response = await apiClient.patch<User>('/api/users/1', partialUpdate);
// With database transaction
const response = await apiClient.patch<User>('/api/users/1', partialUpdate, {
dbTransaction: myTransaction
});Database Transaction Support
When working with database transactions, you can include the Sequelize transaction object in the request config to ensure that failed request logs are included in the same transaction:
import { IApiClientRequestConfig } from '@tomei/general';
import { Transaction } from 'sequelize';
import { sequelize } from 'your-sequelize-instance';
const transaction = await sequelize.transaction();
try {
// Your business logic that might include API calls
const config: IApiClientRequestConfig = {
headers: { 'Authorization': 'Bearer token' },
dbTransaction: transaction
};
const response = await apiClient.post('/api/users', userData, config);
// Other database operations using the same transaction
await someOtherDatabaseOperation(transaction);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}This ensures that if the overall operation fails, the failed request log is also rolled back with the transaction.
Advanced Usage
Base Configuration
You can set base configuration when creating the ApiClient instance:
const apiClient = new ApiClient({
retryCount: 5,
config: {
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Authorization': 'Bearer your-token',
'Content-Type': 'application/json',
'User-Agent': 'MyApp/1.0'
}
}
});
// Now all requests will use the base configuration
const response = await apiClient.get('/users'); // Calls https://api.example.com/usersPer-Request Configuration Override
// Override base configuration for specific requests
const response = await apiClient.get('/users', {
timeout: 30000, // Override the base timeout
headers: {
'Accept': 'application/xml' // Override content type for this request
}
});Custom Headers and Configuration
const config = {
headers: {
'Authorization': 'Bearer your-token',
'Content-Type': 'application/json'
},
timeout: 5000
};
const response = await apiClient.get('/api/protected-resource', config);Using with Custom Axios Configuration
const response = await apiClient.request({
method: 'POST',
url: '/api/upload',
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
},
timeout: 30000
});Retry Logic
The API client automatically retries failed requests with the following behavior:
- Retry Count: Configurable (default: 3 attempts)
- Backoff Strategy: Exponential backoff (500ms × attempt number)
- Retry Sequence: 500ms → 1000ms → 1500ms
// Custom retry configuration
const apiClient = new ApiClient({
retryCount: 5, // Will retry up to 5 times
config: {
baseURL: 'https://api.example.com',
timeout: 10000
}
});Failure Tracking
When all retry attempts are exhausted, the API client automatically logs the failure details to the database using the built-in ApiFailedRequestRepository. The repository is automatically initialized when the ApiClient is instantiated, so no manual setup is required.
The logged information includes:
- RequestId: Unique identifier for the failed request
- URL: The requested endpoint
- Method: HTTP method used
- RequestHeaders: Request headers sent
- RequestBody: Request payload
- ResponseStatus: HTTP status code (if available)
- ResponseBody: Response data (if available)
- ErrorMessage: Error description
- CreatedAt: Timestamp of the failure
Database Setup
To use the failure tracking feature, ensure your database has the api_failed_request table. You can create it using the provided migration:
-- Example table structure
CREATE TABLE api_failed_request (
RequestId VARCHAR(30) PRIMARY KEY,
URL TEXT NOT NULL,
Method VARCHAR(5) NOT NULL,
RequestHeaders JSON NOT NULL,
RequestBody JSON NOT NULL,
ResponseStatus INTEGER,
ResponseBody JSON,
ErrorMessage TEXT,
CreatedAt DATETIME NOT NULL
);Error Handling
try {
const response = await apiClient.get('/api/users');
return response.data;
} catch (error) {
if (error.response) {
// Server responded with error status
console.error('Response error:', error.response.status, error.response.data);
} else if (error.request) {
// Request was made but no response received
console.error('Network error:', error.message);
} else {
// Something else happened
console.error('Error:', error.message);
}
throw error;
}TypeScript Support
The API client is fully typed and supports generic types for request and response data. Use the IApiClientRequestConfig interface for type-safe configuration:
import { IApiClientRequestConfig } from '@tomei/general';
interface User {
id: number;
name: string;
email: string;
}
interface CreateUserRequest {
name: string;
email: string;
}
// Typed requests with config
const config: IApiClientRequestConfig = {
headers: { 'Authorization': 'Bearer token' },
timeout: 10000,
dbTransaction: myTransaction
};
const users = await apiClient.get<User[]>('/api/users', config);
const newUser = await apiClient.post<User>('/api/users', {
name: 'John Doe',
email: '[email protected]'
}, config);Best Practices
- Singleton Pattern: Create a single instance of ApiClient and reuse it throughout your application
- Error Handling: Always wrap API calls in try-catch blocks
- Timeouts: Set appropriate timeouts for your requests
- Headers: Include necessary authentication headers
- Type Safety: Use TypeScript interfaces for request/response data
Example: Complete Integration
import { ApiClient, IApiClientRequestConfig } from '@tomei/general';
import { Transaction } from 'sequelize';
interface User {
id: number;
name: string;
email: string;
}
interface CreateUserRequest {
name: string;
email: string;
}
class UserService {
private apiClient: ApiClient;
constructor() {
this.apiClient = new ApiClient({
retryCount: 3,
config: {
baseURL: 'https://api.example.com',
headers: {
'Authorization': `Bearer ${process.env.API_TOKEN}`
}
}
});
}
async getUsers(): Promise<User[]> {
try {
const response = await this.apiClient.get<User[]>('/api/users');
return response.data;
} catch (error) {
console.error('Failed to fetch users:', error);
throw error;
}
}
async createUser(userData: CreateUserRequest, transaction?: Transaction): Promise<User> {
try {
const config: IApiClientRequestConfig = {
dbTransaction: transaction
};
const response = await this.apiClient.post<User>('/api/users', userData, config);
return response.data;
} catch (error) {
console.error('Failed to create user:', error);
throw error;
}
}
}License
ISC
