Essential utility functions for unit conversion, API interception, event management, and provider services within the QQ mini-program environment.
Convert between upx (universal pixel) units and actual pixels for responsive design.
/**
* Convert upx units to pixels based on device width
* @param upx - Value in upx units
* @param newDeviceWidth - Custom device width (optional)
* @returns Converted pixel value
*/
function upx2px(upx: number, newDeviceWidth?: number): number;Usage Examples:
import { upx2px } from "@dcloudio/uni-mp-qq";
// Convert upx to pixels using default device width
const pixelValue = upx2px(100); // e.g., returns 50 on a 375px wide device
// Convert using custom device width
const customPixelValue = upx2px(100, 750); // Base calculation on 750px width
// Use in dynamic styling
const elementStyle = {
width: upx2px(200) + 'px',
height: upx2px(150) + 'px',
fontSize: upx2px(28) + 'px'
};
// Convert responsive values
const responsiveMargin = upx2px(20); // Scales with device widthAdd and remove interceptors for API calls to handle cross-cutting concerns like authentication, logging, and error handling.
/**
* Add API interceptor for method calls
* @param method - API method name or global interceptor object
* @param option - Interceptor configuration options
*/
function addInterceptor(method: string | InterceptorConfig, option?: InterceptorOptions): void;
/**
* Remove API interceptor
* @param method - API method name or global interceptor object
* @param option - Interceptor configuration to remove (optional)
*/
function removeInterceptor(method: string | InterceptorConfig, option?: InterceptorOptions): void;
interface InterceptorOptions {
/** Called before API execution */
invoke?: (args: any) => any;
/** Called on API success */
success?: (res: any) => any;
/** Called on API failure */
fail?: (res: any) => any;
/** Called after API completion (success or fail) */
complete?: (res: any) => any;
/** Called to transform return value */
returnValue?: (res: any) => any;
}
interface InterceptorConfig {
invoke?: (args: any) => any;
success?: (res: any) => any;
fail?: (res: any) => any;
complete?: (res: any) => any;
returnValue?: (res: any) => any;
}Usage Examples:
import { addInterceptor, removeInterceptor } from "@dcloudio/uni-mp-qq";
// Add global request interceptor
addInterceptor('request', {
invoke(args) {
// Add authentication header
args.header = args.header || {};
args.header['Authorization'] = `Bearer ${getAuthToken()}`;
// Add timestamp
args.header['X-Request-Time'] = Date.now().toString();
console.log('Request intercepted:', args.url);
return args;
},
success(res) {
console.log('Request successful:', res.statusCode);
// Handle token refresh
if (res.statusCode === 401) {
refreshAuthToken();
}
return res;
},
fail(err) {
console.error('Request failed:', err);
// Show error toast for network issues
if (err.errMsg.includes('network')) {
uni.showToast({
title: 'Network Error',
icon: 'none'
});
}
return err;
}
});
// Add interceptor for navigation with analytics
addInterceptor('navigateTo', {
invoke(args) {
// Track page navigation
analyticsTrack('page_navigate', {
from: getCurrentPagePath(),
to: args.url,
timestamp: Date.now()
});
return args;
}
});
// Add global interceptor for all APIs
addInterceptor({
invoke(args) {
console.log('API call intercepted');
return args;
},
returnValue(res) {
// Transform all API responses
if (res && typeof res === 'object') {
res.intercepted = true;
res.timestamp = Date.now();
}
return res;
}
});
// Remove specific interceptor
const authInterceptor = {
invoke(args) {
args.header = args.header || {};
args.header['Authorization'] = getAuthToken();
return args;
}
};
addInterceptor('request', authInterceptor);
// Later remove it
removeInterceptor('request', authInterceptor);
// Remove all interceptors for a method
removeInterceptor('request');Access to pre-built interceptor objects for common functionality.
/**
* Built-in interceptors object
*/
declare const interceptors: {
/** Promise interceptor for handling Promise-based returns */
promiseInterceptor: {
returnValue(res: any): any;
};
};Usage Examples:
import { interceptors, addInterceptor } from "@dcloudio/uni-mp-qq";
// Use built-in promise interceptor
addInterceptor('customAPI', interceptors.promiseInterceptor);
// The promise interceptor handles Promise return values
// It converts [error, data] tuple format to proper Promise resolution/rejectionGet information about available service providers for different functionality areas.
/**
* Get available service providers
* @param options - Provider query options
* @returns Promise resolving with provider information
*/
function getProvider(options: GetProviderOptions): Promise<ProviderResult>;
interface GetProviderOptions {
/** Service type to query */
service: 'oauth' | 'share' | 'payment' | 'push';
/** Success callback */
success?: (res: ProviderResult) => void;
/** Failure callback */
fail?: (res: any) => void;
/** Completion callback */
complete?: (res: any) => void;
}
interface ProviderResult {
/** Service type */
service: string;
/** Available providers */
provider: string[];
/** Result message */
errMsg: string;
}Usage Examples:
import { getProvider } from "@dcloudio/uni-mp-qq";
// Check available OAuth providers
const oauthProviders = await getProvider({
service: 'oauth'
});
console.log('OAuth providers:', oauthProviders.provider); // ['qq']
// Check available share providers
const shareProviders = await getProvider({
service: 'share'
});
console.log('Share providers:', shareProviders.provider); // ['qq']
// Check available payment providers
const paymentProviders = await getProvider({
service: 'payment'
});
console.log('Payment providers:', paymentProviders.provider); // ['qqpay']
// Check available push providers
const pushProviders = await getProvider({
service: 'push'
});
console.log('Push providers:', pushProviders.provider); // ['qq']
// Use callback style
getProvider({
service: 'oauth',
success: (res) => {
if (res.provider.includes('qq')) {
// QQ OAuth is available
initializeQQLogin();
}
},
fail: (err) => {
console.error('Failed to get providers:', err);
}
});Create responsive media query observers for handling different screen sizes and orientations.
/**
* Create media query observer for responsive design
* @returns MediaQueryObserver instance
*/
function createMediaQueryObserver(): MediaQueryObserver;
interface MediaQueryObserver {
/**
* Observe media query changes
* @param descriptor - Media query conditions
* @param callback - Callback function for query changes
* @returns Whether current conditions match
*/
observe(descriptor: MediaQueryDescriptor, callback: (res: MediaQueryResult) => void): boolean;
/** Disconnect the observer */
disconnect(): void;
}
interface MediaQueryDescriptor {
/** Minimum width in pixels */
minWidth?: number;
/** Maximum width in pixels */
maxWidth?: number;
/** Exact width in pixels */
width?: number;
/** Minimum height in pixels */
minHeight?: number;
/** Maximum height in pixels */
maxHeight?: number;
/** Exact height in pixels */
height?: number;
/** Screen orientation */
orientation?: 'portrait' | 'landscape';
}
interface MediaQueryResult {
/** Whether the media query matches */
matches: boolean;
}Usage Examples:
import { createMediaQueryObserver } from "@dcloudio/uni-mp-qq";
// Create media query observer
const mediaQueryObserver = createMediaQueryObserver();
// Observe screen width changes
mediaQueryObserver.observe({
minWidth: 768
}, (res) => {
if (res.matches) {
console.log('Screen is wide enough for tablet layout');
enableTabletLayout();
} else {
console.log('Screen is narrow, use mobile layout');
enableMobileLayout();
}
});
// Observe orientation changes
mediaQueryObserver.observe({
orientation: 'landscape'
}, (res) => {
if (res.matches) {
console.log('Device is in landscape mode');
adjustForLandscape();
} else {
console.log('Device is in portrait mode');
adjustForPortrait();
}
});
// Complex media query
mediaQueryObserver.observe({
minWidth: 480,
maxWidth: 768,
orientation: 'portrait'
}, (res) => {
if (res.matches) {
console.log('Medium-sized portrait screen');
enableMediumPortraitLayout();
}
});
// Disconnect observer when no longer needed
// mediaQueryObserver.disconnect();The upx2px function enables responsive design across different device sizes:
// Responsive component styling
const createResponsiveStyle = (baseUpx) => ({
mobile: upx2px(baseUpx, 375), // Based on mobile width
tablet: upx2px(baseUpx, 768), // Based on tablet width
desktop: upx2px(baseUpx, 1024) // Based on desktop width
});
const textSizes = createResponsiveStyle(28);
// textSizes.mobile, textSizes.tablet, textSizes.desktopInterceptors can be chained and combined for complex processing:
// Authentication interceptor
const authInterceptor = {
invoke(args) {
args.header = args.header || {};
args.header['Authorization'] = getAuthToken();
return args;
}
};
// Logging interceptor
const loggingInterceptor = {
invoke(args) {
console.log('API Call:', args);
return args;
},
success(res) {
console.log('API Success:', res);
return res;
}
};
// Rate limiting interceptor
const rateLimitInterceptor = {
invoke(args) {
if (!checkRateLimit(args.url)) {
throw new Error('Rate limit exceeded');
}
return args;
}
};
// Apply multiple interceptors
addInterceptor('request', authInterceptor);
addInterceptor('request', loggingInterceptor);
addInterceptor('request', rateLimitInterceptor);Use provider information to enable/disable features:
// Initialize features based on available providers
async function initializeApp() {
const [oauth, share, payment] = await Promise.all([
getProvider({ service: 'oauth' }),
getProvider({ service: 'share' }),
getProvider({ service: 'payment' })
]);
// Enable features based on available providers
if (oauth.provider.includes('qq')) {
enableQQLogin();
}
if (share.provider.includes('qq')) {
enableQQSharing();
}
if (payment.provider.includes('qqpay')) {
enableQQPay();
}
}qq - QQ login and user authorizationqq - Share to QQ friends and groupsqqpay - QQ Pay payment processingqq - QQ push notification servicesupx2px conversion