Essential helper functions for common operations, data conversions, and API management.
Convert between different measurement units used in uni-app.
/**
* Convert upx units to pixels
* @param upx - Value in upx units
* @returns Converted pixel value
*/
function upx2px(upx: number): number;Usage Examples:
import uni from "@dcloudio/uni-app-plus";
// Convert design measurements to actual pixels
const width = uni.upx2px(750); // Convert 750upx to pixels
const height = uni.upx2px(400);
const margin = uni.upx2px(30);
console.log(`Element size: ${width}px × ${height}px`);
console.log(`Margin: ${margin}px`);
// Use in dynamic styling
const elementStyle = {
width: uni.upx2px(200) + 'px',
height: uni.upx2px(100) + 'px',
fontSize: uni.upx2px(28) + 'px'
};Convert between different data formats for cross-platform compatibility.
/**
* Convert base64 string to ArrayBuffer
* @param base64 - Base64 encoded string
* @returns ArrayBuffer representation
*/
function base64ToArrayBuffer(base64: string): ArrayBuffer;
/**
* Convert ArrayBuffer to base64 string
* @param arrayBuffer - ArrayBuffer to convert
* @returns Base64 encoded string
*/
function arrayBufferToBase64(arrayBuffer: ArrayBuffer): string;Usage Examples:
// Convert image to ArrayBuffer for processing
const base64Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==';
const imageData = uni.base64ToArrayBuffer(base64Image.split(',')[1]);
// Process the ArrayBuffer data
processImageData(imageData);
// Convert back to base64 for storage or transmission
const processedBase64 = uni.arrayBufferToBase64(imageData);
console.log('Processed image:', processedBase64);
// File upload example
uni.chooseImage({
success: (res) => {
const filePath = res.tempFilePaths[0];
// Read file as ArrayBuffer
const fs = uni.getFileSystemManager();
fs.readFile({
filePath: filePath,
success: (fileRes) => {
const arrayBuffer = fileRes.data;
const base64 = uni.arrayBufferToBase64(arrayBuffer);
// Upload as base64
uploadAsBase64(base64);
}
});
}
});Add global or method-specific interceptors to modify API behavior.
/**
* Add API interceptor
* @param method - API method name or global interceptor object
* @param interceptor - Interceptor configuration
*/
function addInterceptor(method: string | object, interceptor?: InterceptorOptions): void;
/**
* Remove API interceptor
* @param method - API method name or global interceptor object
* @param interceptor - Interceptor configuration to remove
*/
function removeInterceptor(method: string | object, interceptor?: InterceptorOptions): void;
interface InterceptorOptions {
invoke?: (args: any) => any;
success?: (result: any) => any;
fail?: (error: any) => any;
complete?: (result: any) => any;
returnValue?: (result: any) => any;
}Usage Examples:
// Global request interceptor
uni.addInterceptor({
invoke: (args) => {
console.log('API invoked:', args);
// Add authentication token to all requests
if (args.url && !args.header) {
args.header = {};
}
if (args.header && !args.header.Authorization) {
args.header.Authorization = 'Bearer ' + getAuthToken();
}
return args;
},
success: (result) => {
console.log('API success:', result);
return result;
},
fail: (error) => {
console.error('API error:', error);
// Handle common errors
if (error.statusCode === 401) {
handleAuthError();
}
return error;
}
});
// Method-specific interceptor for requests
uni.addInterceptor('request', {
invoke: (args) => {
// Add base URL to all requests
if (!args.url.startsWith('http')) {
args.url = 'https://api.example.com' + args.url;
}
// Add common headers
args.header = {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
...args.header
};
return args;
},
success: (result) => {
// Log successful requests
console.log('Request successful:', result.statusCode);
return result;
},
fail: (error) => {
// Retry logic for failed requests
if (error.statusCode >= 500) {
console.log('Server error, retrying...');
// Implement retry logic here
}
return error;
}
});
// Storage interceptor for data validation
uni.addInterceptor('setStorage', {
invoke: (args) => {
// Validate data before storing
if (typeof args.data === 'object') {
try {
JSON.stringify(args.data);
} catch (e) {
throw new Error('Data is not serializable');
}
}
// Add timestamp to stored data
args.data = {
_timestamp: Date.now(),
_data: args.data
};
return args;
}
});
// Remove interceptor when no longer needed
uni.removeInterceptor('request');
// Custom interceptor for showToast
uni.addInterceptor('showToast', {
invoke: (args) => {
// Ensure minimum duration
if (!args.duration || args.duration < 1000) {
args.duration = 1500;
}
// Default to success icon if not specified
if (!args.icon) {
args.icon = 'success';
}
return args;
}
});Access to the interceptors configuration object.
/**
* Interceptors configuration object
*/
interface Interceptors {
promiseInterceptor: {
returnValue: (result: any) => any;
};
}
declare const interceptors: Interceptors;Built-in promise interceptor for handling async operations.
// Built-in promise interceptor that formats return values
const promiseInterceptor = {
returnValue: (result: any) => {
// Converts promise results to [error, data] format
// Success: [null, data]
// Error: [error, null]
return result;
}
};Usage Example:
// The promise interceptor automatically formats async API results
async function fetchUserData() {
try {
// Using promise-style API call
const [error, result] = await uni.request({
url: '/api/user/profile'
});
if (error) {
console.error('Request failed:', error);
return null;
}
return result.data;
} catch (err) {
console.error('Unexpected error:', err);
return null;
}
}
// Alternative callback style
uni.request({
url: '/api/user/profile',
success: (result) => {
console.log('User data:', result.data);
},
fail: (error) => {
console.error('Request failed:', error);
}
});Helper functions for common error handling patterns.
// Common error handling patterns used internally
interface ErrorHandler {
handleNetworkError: (error: any) => void;
handleAuthError: (error: any) => void;
handleValidationError: (error: any) => void;
}Usage Example:
// Custom error handling utility
const errorHandler = {
handleNetworkError: (error) => {
if (error.errMsg && error.errMsg.includes('timeout')) {
uni.showToast({
title: 'Network timeout, please try again',
icon: 'none'
});
} else if (error.statusCode >= 500) {
uni.showToast({
title: 'Server error, please try later',
icon: 'none'
});
}
},
handleAuthError: (error) => {
if (error.statusCode === 401) {
uni.showModal({
title: 'Authentication Required',
content: 'Please log in to continue',
success: (res) => {
if (res.confirm) {
uni.navigateTo({
url: '/pages/login/login'
});
}
}
});
}
}
};
// Use with interceptors
uni.addInterceptor('request', {
fail: (error) => {
errorHandler.handleNetworkError(error);
errorHandler.handleAuthError(error);
return error;
}
});Utility functions for detecting the current runtime environment.
// Environment detection (available through canIUse)
const environmentCheck = {
isApp: () => uni.canIUse('getSystemInfo'),
isAndroid: () => {
const systemInfo = uni.getSystemInfoSync();
return systemInfo.platform === 'android';
},
isIOS: () => {
const systemInfo = uni.getSystemInfoSync();
return systemInfo.platform === 'ios';
}
};interface InterceptorHook {
(args: any): any;
}
interface MethodInterceptor {
invoke?: InterceptorHook;
success?: InterceptorHook;
fail?: InterceptorHook;
complete?: InterceptorHook;
returnValue?: InterceptorHook;
}
interface GlobalInterceptor {
[methodName: string]: MethodInterceptor;
}interface ConversionResult {
value: number;
unit: string;
}
interface DataFormatOptions {
encoding?: 'utf8' | 'base64' | 'hex';
format?: 'json' | 'string' | 'buffer';
}