@ticatec/axios-restful-service
v0.5.0
Published
A modular REST service implementation based on Axios with separate classes for REST operations (AxiosRestService) and file operations (AxiosFileService). Supports GET, POST, PUT, DELETE, PATCH, file upload/download with progress tracking, interceptors, an
Readme
@ticatec/axios-restful-service
A comprehensive REST service implementation based on Axios, designed to simplify HTTP request handling with enhanced features for modern web applications.
This package is ESM-only (v0.5.0+).
中文 | English
Features
- 🔄 Unified HTTP Request Handling: Encapsulates all common HTTP methods (GET, POST, PUT, DELETE, PATCH)
- 📁 File Operations: Supports single file uploads with progress tracking and file downloads via separate service
- 🏗️ Modular Design: Separate service classes for REST operations and file operations
- 🔗 Request/Response Interceptors: Customizable pre-request and post-response processing
- ⚠️ Enhanced Error Handling: Comprehensive error handling with structured
ApiErrorobjects - 🐛 Debug Mode: Built-in debugging capabilities for development
- ⏰ Configurable Timeouts: Flexible timeout settings per request
- 🚫 Upload Cancellation: Asynchronous uploads with cancellation support
- 🔒 Credential Support: Built-in support for cookies and authentication
Installation
npm install @ticatec/axios-restful-serviceImportant: This package requires axios >= 1.15.0 and @ticatec/restful_service_api >= 0.5.0 as peer dependencies. Make sure to install them in your project:
npm install axios @ticatec/restful_service_apiQuick Start
import AxiosRestService from '@ticatec/axios-restful-service';
// Create a service instance
const apiService = new AxiosRestService('https://api.example.com');
// Make a simple GET request
const users = await apiService.get('/users');
console.log(users);Advanced Usage
With Interceptors and Error Handling
import AxiosRestService from '@ticatec/axios-restful-service';
import type { PreInterceptorResult, ErrorHandler, PreInterceptor, PostInterceptor } from '@ticatec/restful_service_api';
// Error handling function
const errorHandler: ErrorHandler = (ex) => {
if (ex instanceof ApiError) {
console.error('API Error:', ex.statusCode, ex.data);
} else {
console.error('Other Error:', ex.message);
}
return true; // Indicates the error has been handled
};
// Pre-request interceptor
const preInvoke: PreInterceptor = (method, url): PreInterceptorResult => {
return {
headers: {
Authorization: 'Bearer ' + getAuthToken(),
'X-Client-Version': '1.0.0'
},
timeout: 30000 // 30 seconds timeout
};
};
// Post-response interceptor
const postInvoke: PostInterceptor = async (data) => {
console.log('Response received:', data);
// Transform response data if needed
return data;
};
// Create service with interceptors
const apiService = new AxiosRestService(
'https://api.example.com',
errorHandler,
preInvoke,
postInvoke
);
// Enable debug mode
AxiosRestService.setDebug(true);HTTP Methods
// GET request with query parameters
const users = await apiService.get('/users', { page: 1, limit: 10 });
// POST request with JSON data
const newUser = await apiService.post('/users', {
name: 'John Doe',
email: '[email protected]'
});
// POST request with options
const result = await apiService.post('/users', userData, {
params: { action: 'create' },
contentType: 'application/json',
dataProcessor: (data) => data.result
});
// PUT request to update data
const updatedUser = await apiService.put('/users/123', {
name: 'John Smith'
});
// PATCH request for partial update
const partialUpdate = await apiService.patch('/users/123', {
status: 'active'
});
// DELETE request
await apiService.del('/users/123');
// DELETE request with options
await apiService.del('/users/123', null, {
params: { permanent: true }
});Using File Service
For file operations, use the AxiosFileService class:
import { AxiosFileService } from '@ticatec/axios-restful-service';
// Create a file service instance
const fileService = new AxiosFileService('https://api.example.com');
// You can also use interceptors and error handlers
const fileService = new AxiosFileService(
'https://api.example.com',
errorHandler,
preInvoke,
postInvoke
);File Upload
Simple Upload
const fileInput = document.getElementById('file') as HTMLInputElement;
const file = fileInput.files[0];
try {
const result = await fileService.upload('/upload', { type: 'avatar' }, file);
console.log('Upload successful:', result);
} catch (error) {
console.error('Upload failed:', error);
}Asynchronous Upload with Progress
import type { UploadCallback } from '@ticatec/restful_service_api';
const callback: UploadCallback = {
progressUpdate: (progress) => {
console.log(`Upload progress: ${progress}%`);
// Update progress bar
document.getElementById('progress').style.width = `${progress}%`;
},
onCompleted: (data) => {
console.log('Upload completed:', data);
},
handleError: (error) => {
console.error('Upload error:', error);
}
};
// Start upload with progress tracking
const uploadProgress = await fileService.asyncUpload(
'/upload',
{ type: 'document' },
file,
callback
);
// Cancel upload if needed
setTimeout(() => {
uploadProgress.cancel();
console.log('Upload cancelled');
}, 5000);File Download
// Download a file
try {
await fileService.download('/download/report.pdf', 'monthly-report.pdf', {
month: 'january',
year: 2024
});
console.log('Download started');
} catch (error) {
console.error('Download failed:', error);
}Custom Content Types
// Send form data
await apiService.post('/form-submit', formData, {
contentType: 'application/x-www-form-urlencoded'
});
// Send XML data
await apiService.post('/xml-endpoint', xmlData, {
contentType: 'application/xml'
});
// With multiple options
await apiService.put('/update', data, {
params: { id: 123 },
contentType: 'application/json',
dataProcessor: (response) => response.data
});API Reference
Service Classes
This package provides two main service classes:
- AxiosRestService (default export) - For standard REST operations
- AxiosFileService - For file upload/download operations
Both classes share the same constructor signature and interceptor support.
Constructor
constructor(
root: string,
errorHandler?: ErrorHandler,
preInvoke?: PreInterceptor,
postInvoke?: PostInterceptor
)root: Base URL for all API requestserrorHandler: Optional error handler functionpreInvoke: Optional pre-request interceptorpostInvoke: Optional post-response interceptor
Static Methods
AxiosRestService.setDebug(value: boolean): Enable/disable debug logging for all services
AxiosRestService Methods
HTTP Methods
get(url, params?, dataProcessor?): GET requestpost(url, data?, options?): POST requestoptions.params: Query parametersoptions.contentType: Content-Type header valueoptions.dataProcessor: Function to process response data
put(url, data?, options?): PUT request- Accepts same options as POST
patch(url, data?, options?): PATCH request for partial updates- Accepts same options as POST
del(url, data?, options?): DELETE request- Accepts same options as POST
AxiosFileService Methods
File Operations
upload(url, params, file, fileKey?, dataProcessor?): Upload single filefileKey: Form field name (defaults to 'file')
asyncUpload(url, params, file, callback, fileKey?): Upload with progress tracking- Returns
UploadProgressobject withcancel()method
- Returns
download(url, filename, params, method?, formData?): Download filemethod: HTTP method (defaults to 'get')formData: Optional form data for POST downloads
Error Handling
The service uses structured error handling with ApiError objects that contain:
statusCode: HTTP status code (-1 for network errors)data: Detailed error information including:code: Custom error codemessage: Error messagenetworkError: Boolean indicating network issuesoriginalCode/originalMessage: Original error details
Network Error Codes
100: General network error101: Request timeout102: Network unavailable103: Request cancelled104: Host not found105: Connection refused106: Configuration error
TypeScript Support
This package is written in TypeScript and provides full type definitions. All interfaces are imported from @ticatec/restful_service_api:
ESM Usage
This package is a pure ESM module and cannot be used with require(). Use import statements:
// ✅ Correct - ESM import
import AxiosRestService from '@ticatec/axios-restful-service';
import { AxiosFileService } from '@ticatec/axios-restful-service';
// ❌ Wrong - CommonJS require
// const AxiosRestService = require('@ticatec/axios-restful-service');If you're using CommonJS, consider updating to ESM or use a dynamic import:
const { default: AxiosRestService } = await import('@ticatec/axios-restful-service');PreInterceptorPostInterceptorErrorHandlerDataProcessorUploadCallbackUploadProgressPreInterceptorResult
Browser Compatibility
- Modern browsers with ES6+ support
- Requires
FormDataAPI for file uploads - Requires
BlobAPI for file downloads
Dependencies
- axios - HTTP client
- @ticatec/restful_service_api - Interface definitions
Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.
License
MIT License - see LICENSE file for details.
