VJSP Vue3 Framework API Documentation
Overview
VJSP Vue3 Framework provides a complete interface management and request encapsulation mechanism to support enterprise-level middle and back-office application development needs. The framework is deeply encapsulated based on Axios, offering unified request management, error handling, security protection, and performance optimization features.
1. Interface Management and Request Encapsulation Mechanism
1.1 Request Encapsulation Architecture
The framework adopts a layered architecture design, dividing request processing into multiple layers:
- Axios Instance Layer [axios/service.ts]: Configures base request instances, including core functions like request retry and cancellation
- Interceptor Layer [axios/config.ts]: Handles request/response interception, implementing unified error handling and business status code parsing
- API Service Layer [axios/index.ts]: Business interface encapsulation, providing unified request method calling interfaces
- Type Definition Layer [types/api]: TypeScript type support, ensuring type safety
1.2 Core Request Encapsulation
The framework provides a unified request encapsulation mechanism supporting HTTP methods like GET, POST, PUT, DELETE:
Request Method Usage Mechanism
The framework provides a unified HTTP request encapsulation mechanism supporting standard HTTP method calls:
Request Method Support Mechanism:
- GET Request Mechanism: Supports query parameter passing, automatically handles URL encoding and parameter serialization
- POST Request Mechanism: Supports request body data passing, automatically handles JSON serialization and content type setting
- PUT Request Mechanism: Supports resource update operations, provides complete data update functionality
- DELETE Request Mechanism: Supports resource deletion operations, provides secure deletion confirmation mechanism
Request Processing Flow:
- Request Preprocessing: Automatically adds authentication tokens, sets request headers, handles parameter serialization
- Request Sending: Sends requests to server through underlying HTTP client
- Response Processing: Unified processing of response data, status code validation, error interception
- Result Return: Returns formatted response data, including business status codes and data content
Core Feature Description
Security Mechanism
- Automatic rate limiting: Prevents API requests from being too frequent
- CSRF protection: Cross-site request forgery protection for sensitive operations
- Token auto-injection: Automatically carries user authentication tokens during requests
Error Handling
- Unified error interception: Automatically handles network errors and business errors
- Friendly prompts: Uses message manager to display error information
- Retry mechanism: Automatic retry for failed requests
Function Support
- Request cancellation: Supports canceling ongoing requests
- File upload: Supports multipart/form-data format
- Type safety: Complete TypeScript type support
1.3 Business Status Code System
The framework defines a complete business status code system for unified handling of various business scenarios. Status code definitions are located in the src/constants/index.ts file.
Core Status Code Definitions
- SUCCESS_CODE = 'A0000': Request successful
- RATE_LIMIT_ERROR_CODE = 'A0006': Rate limit error
- CSRF_VALIDATION_ERROR_CODE = 'A0007': CSRF validation failed
Status Code Processing Mechanism
The framework handles various business status codes through a unified error handling mechanism, ensuring good user experience in different scenarios.
Status Code Processing Flow:
- Status Code Identification: Identifies request results based on business status codes in responses
- Error Classification Processing: Classifies status codes into different categories like success, warning, error
- User Prompt Display: Displays appropriate user prompt information through message manager
- Business Logic Processing: Executes corresponding business logic based on status codes
Core Status Code Processing Strategy:
- Success Status Code (A0000): Normally returns data, continues subsequent business logic
- Authentication-related Error Codes: Automatically redirects to login page, clears user session information
- Permission-related Error Codes: Displays insufficient permission prompts, restricts related operations
- Business Logic Error Codes: Displays specific error information, guides users to correct operations
- System Protection Error Codes: Displays system protection prompts, prevents malicious requests
1.4 Type Safety Support
The framework provides complete TypeScript type safety support, ensuring type safety and code quality during development.
Type Definition Mechanism
- Modular Type Definitions: Each business module has independent type definition files
- Request/Response Types: Defines complete request parameter and response data types for each API interface
- Business Entity Types: Defines data structures for business entities like users, roles, menus
Type Safety Features
- Compile-time Type Checking: Catches type errors during development phase
- Intelligent Code Hints: IDE provides complete type hints and auto-completion
- Interface Contract Guarantee: Ensures consistency of frontend-backend interface data formats
- Refactoring Safety: Type system helps safely refactor code
Type Safety Mechanism
The framework provides compile-time type safety guarantees through a complete TypeScript type system:
Type Safety Mechanism Features:
- Interface Contract Guarantee: Ensures consistency of frontend-backend interface data formats through type definitions
- Compile-time Checking: Catches type errors during development phase, avoiding runtime exceptions
- Intelligent Hint Support: IDE provides complete type hints and auto-completion functionality
- Refactoring Safety: Type system helps safely refactor code and maintain modules
Type Safety Implementation Mechanism:
- Modular Type Definitions: Each business module has independent type definition files
- Request/Response Type Mapping: Defines complete request parameter and response data types for each API interface
- Business Entity Typing: Defines data structures for business entities like users, roles, menus
- Type Inference Mechanism: Automatically infers parameter types and return value types for API calls
2. Business Module Development Guide
2.1 Developing New API Module
Step 1: Create Type Definitions
// src/types/api/module/product.d.ts
export interface ProductItem {
id: string
name: string
price: number
stock: number
status: number
category: string
createTime: string
}
export interface ProductListRequest {
pageNum: number
pageSize: number
name?: string
category?: string
status?: number
}
export interface ProductListResponse {
list: ProductItem[]
total: number
}Step 2: Create API Service
// src/api/product/index.ts
import request from '@/axios'
import type {
ProductItem,
ProductListRequest,
ProductListResponse,
} from '@/types/api/module/product'
/**
* Get product list
* @param params
* @returns
*/
export function getProductListApi(params: ProductListRequest) {
return request.get({
url: '/modules/product',
params,
})
}
/**
* Add product
* @param data
* @returns
*/
export function addProductApi(data: ProductItem) {
return request.post({
url: '/modules/product',
data,
})
}
/**
* Delete product
* @param id
* @returns
*/
export function deleteProductApi(id: string) {
return request.delete({
url: `/modules/product/${id}`,
})
}
/**
* Batch delete products
* @param ids
* @returns
*/
export function batchDeleteProductApi(ids: string[]) {
return request.delete({
url: '/modules/product/batchRemove',
data: ids,
})
}
/**
* Get product details
* @param id
* @returns
*/
export function getProductApi(id: string) {
return request.get<ProductItem>({
url: `/modules/product/${id}`,
})
}
/**
* Update product
* @param data
* @returns
*/
export function updateProductApi(data: ProductItem) {
return request.put({
url: `/modules/product/${data.id}`,
data,
})
}2.2 Using API in Components
Basic Usage
<template>
<div>
<el-table :data="productList" v-loading="loading">
<el-table-column prop="name" label="Product Name" />
<el-table-column prop="price" label="Price" />
<el-table-column prop="stock" label="Stock" />
</el-table>
<el-pagination
v-model:current-page="currentPage"
v-model:page-size="pageSize"
:total="total"
@current-change="handlePageChange"
/>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getProductListApi } from '@/api/product'
import type { ProductItem, ProductListRequest } from '@/types/api/module/product'
const productList = ref<ProductItem[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
// Load product list
const loadProductList = async () => {
loading.value = true
try {
const response = await getProductListApi({
pageNum: currentPage.value,
pageSize: pageSize.value,
})
productList.value = response.data.list
total.value = response.data.total
} catch (error) {
console.error('Failed to load product list:', error)
} finally {
loading.value = false
}
}
// Pagination handling
const handlePageChange = (page: number) => {
currentPage.value = page
loadProductList()
}
onMounted(() => {
loadProductList()
})
</script>Using Composition API Encapsulation
// composables/useProduct.ts
import { ref, computed } from 'vue'
import { getProductListApi, addProductApi, updateProductApi, deleteProductApi } from '@/api/product'
import type { ProductItem, ProductListRequest } from '@/types/api/module/product'
export function useProduct() {
const productList = ref<ProductItem[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
// Computed properties
const hasMore = computed(() => {
return currentPage.value * pageSize.value < total.value
})
// Load product list
const loadProductList = async (params?: Partial<ProductListRequest>) => {
loading.value = true
try {
const response = await getProductListApi({
pageNum: currentPage.value,
pageSize: pageSize.value,
...params,
})
productList.value = response.data.list
total.value = response.data.total
} catch (error) {
console.error('Failed to load product list:', error)
throw error
} finally {
loading.value = false
}
}
// Create product
const createProduct = async (data: ProductItem) => {
try {
await addProductApi(data)
// Reload list
await loadProductList()
} catch (error) {
console.error('Failed to create product:', error)
throw error
}
}
// Reset pagination
const resetPagination = () => {
currentPage.value = 1
total.value = 0
}
return {
productList,
loading,
currentPage,
pageSize,
total,
hasMore,
loadProductList,
createProduct,
resetPagination,
}
}2.3 Best Practices
Error Handling Best Practices
The framework recommends a layered error handling strategy to ensure good user experience and system stability in different scenarios.
Core Processing Strategy:
- Async Operation Wrapping: Use try-catch structure to wrap all asynchronous API calls
- Unified Error Handling: Display user-friendly error information through message manager
- Error Log Recording: Record detailed error information in console for debugging
- Duplicate Prevention: Avoid frequent display of same error messages
Processing Flow:
- Exception Capture: Capture various exceptions that may occur during API calls
- Error Classification: Differentiate processing based on error types
- User Prompt: Display appropriate user prompts through message manager
- Log Recording: Record detailed error information for problem investigation
- State Recovery: Ensure application can continue running normally after errors
Request Cancellation Best Practices
The framework provides a complete request cancellation mechanism to help developers effectively manage asynchronous requests in component lifecycle, avoiding memory leaks and invalid request processing.
Core Cancellation Strategy:
- Component Lifecycle Management: Automatically cancel related requests when component unmounts
- Precise Cancellation Control: Supports canceling specific endpoints or all requests
- Error Type Identification: Distinguishes request cancellation errors from other error types
- Resource Cleanup: Ensures related resources are properly released after request cancellation
Application Scenarios:
- Component Unmounting: Cancel ongoing requests when user leaves page
- Duplicate Requests: Avoid duplicate request competition for same data
- User Operations: User actively cancels long-running requests
- Condition Changes: Cancel old requests when request conditions change
Implementation Mechanism:
- Request Identification: Generate unique identifiers for each request for precise cancellation
- Cancellation Tokens: Use AbortController to implement request cancellation functionality
- State Management: Track request status and cancellation timing
- Error Handling: Distinguish request cancellation errors from real error situations
3. Authentication Authorization and Security Mechanism
3.1 Authentication Mechanism
Login Authentication Flow
The framework provides standardized login authentication flow to ensure security and consistency of user identity verification.
Authentication Flow Mechanism:
- Credential Verification: User submits username and password for identity verification
- Token Generation: Server generates access token after successful verification
- Token Storage: Use token manager to securely store token information
- User Information Management: Store and synchronize basic user information
- State Synchronization: Update application authentication status and route permissions
Security Features:
- Secure Transmission: All authentication requests transmitted through HTTPS encryption
- Token Protection: Token manager provides secure token storage mechanism
- Session Management: Supports session expiration and automatic renewal
- Error Handling: Unified authentication failure handling mechanism
Flow Control:
- Login Verification: Verify validity of user credentials
- State Update: Update global authentication status
- Route Navigation: Page navigation based on authentication results
- Error Feedback: Provide clear error prompt information
Token Management Mechanism
The framework adopts a secure token management mechanism, implementing full lifecycle management of access tokens and refresh tokens through a dedicated token manager. This mechanism ensures security and reliability of user authentication status.
Core Function Features:
Token Storage Security
- Use secure storage methods to manage access tokens and refresh tokens
- Support automatic management of token expiration time
- Prevent token leakage and illegal access
Token Lifecycle Management
- Automatically detect token expiration status
- Support token refresh and automatic renewal
- Provide complete token cleanup mechanism
Security Protection Measures
- Token storage encryption protection
- Prevent token replay attacks
- Support token invalidation detection
Work Mechanism Flow:
- Token Acquisition: Obtain access token and refresh token after successful user login
- Token Storage: Securely store token information and record expiration time
- Token Verification: Verify token validity before each request
- Token Refresh: Automatically use refresh token to obtain new token when detecting token expiration
- Token Cleanup: Automatically clean token information when user logs out or detects abnormalities
3.2 Security Protection Mechanism
Rate Limiting Mechanism
The framework implements a multi-level rate limiting mechanism, providing global, user, and endpoint-level request frequency control through the RateLimiter class. This mechanism is based on time window algorithm, supporting configuration of maximum request count and time window size, effectively preventing API abuse and DDoS attacks.
Core Features:
- Multi-level limits: Supports four dimensions of frequency control: global, user, endpoint, user-endpoint
- Time window algorithm: Based on sliding time window statistics for request count
- Automatic cleanup: Regularly clean expired request records to avoid memory leaks
- Flexible configuration: Supports different limit strategies for different endpoints
CSRF Protection Mechanism
The framework adopts a dual-verification CSRF protection mechanism, ensuring request legitimacy through random tokens and request header verification. The protection mechanism includes token generation, storage, verification, and automatic refresh functions.
Protection Flow:
- Token generation: Create unique tokens using cryptographically secure random number generator
- Token storage: Store tokens on client side and set reasonable expiration time
- Request verification: Verify CSRF token validity for sensitive operations
- Automatic refresh: Automatically generate new tokens when tokens expire
Security Manager
The security manager uniformly manages all security-related functions, including request permission checks, CSRF header generation, and security policy configuration. Through interceptor mechanism, security checks are performed before request sending to ensure system security.
Function Responsibilities:
- Request permission verification: Check user access permissions to endpoints
- Security header management: Automatically add security-related request headers like CSRF
- Policy configuration: Uniformly manage all security-related configuration parameters
3.3 Error Handling Mechanism
Unified Error Handling Mechanism
VJSP Vue3 Framework adopts a layered error handling mechanism, implementing unified business status code processing logic through response interceptors. This mechanism can intelligently identify different types of errors and provide corresponding user prompts and system processing.
Processing Layers:
- Business Status Code Processing: Targeted processing based on predefined business status codes
- HTTP Status Code Processing: Handle network-level error statuses
- Special Scenario Processing: Differentiated processing for special scenarios like file streams, authentication expiration
Core Functions:
- Status code mapping: Map business status codes to specific user prompts and system behaviors
- Automatic logout: Automatically execute logout process when detecting authentication expiration
- Error information standardization: Unify error information format and display method
- Duplicate prevention: Avoid repeated display of same error messages
Network Error Handling Mechanism
The framework implements a complete network error handling mechanism that can identify different types of network exceptions and provide friendly user prompts. Processing scope includes common network issues like request timeout, server errors, network connection interruptions.
Error Type Identification:
- Request timeout: ECONNABORTED error code processing
- Server errors: HTTP 5xx status code processing
- Network connection: Offline status detection and processing
- General errors: Unified processing of other network exceptions
Message Manager Mechanism
The message manager adopts duplicate prevention mechanism, avoiding frequent display of same messages through time interval control and message content deduplication. This mechanism is based on Element Plus message components, providing unified error, warning, success, and information prompt management.
Core Features:
- Message deduplication: Same message only displayed once within certain time interval
- Priority management: Display priority control for different message types
- Status tracking: Record message display status and frequency
- Flexible configuration: Support custom message display intervals and styles
4. Performance Optimization and Monitoring
4.1 Cache Optimization
General Cache Mechanism
The project adopts a unified cache management mechanism, providing standardized data caching functionality through the CacheUtil class. This mechanism supports multiple storage strategies and advanced features, ensuring data security and performance.
Core Features:
- Storage Strategy Selection: Supports both localStorage and sessionStorage storage methods
- Data Encryption: Optional data encryption function to protect sensitive information
- Expiration Management: Automatically clean expired cache data
- Type Safety: Provides complete TypeScript type support
Function Scope:
- Cache setting: Supports setting cache expiration time and encryption options
- Cache retrieval: Automatically handles data decryption and expiration checking
- Cache management: Provides cache removal, clearing, and status checking functions
- Error handling: Complete error handling and logging
Dictionary Data Cache Mechanism
The dictionary data in the project adopts a specialized caching mechanism, combining data caching and request retry functionality to ensure reliability and performance of dictionary data.
Cache Strategy:
- Time Window Cache: Set 5-minute valid cache time
- Status Management: Track data loading status and error information
- Intelligent Refresh: Supports forced refresh and cache validity checking
Retry Mechanism:
- Exponential Backoff: Retry delay increases exponentially with retry count
- Maximum Retry Limit: Maximum 3 retries to avoid infinite retrying
- Status Reset: Reset retry count after successful data acquisition
Core Functions:
- Automatic cache management: Automatically determine cache validity based on time window
- Concurrency control: Prevent duplicate requests for same data
- Error recovery: Automatic retry mechanism for network exceptions
- Status synchronization: Ensure correctness of data loading status
4.2 Request Optimization
Request Retry Mechanism
The project implements an intelligent request retry mechanism, achieving automatic recovery from network exceptions and performance optimization through interceptor pattern.
Retry Strategy:
- Exponential Backoff Algorithm: Retry delay increases exponentially with retry count, avoiding server pressure
