pet/http/api/common.js

513 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 通用API接口模块
*
* @fileoverview 提供文件上传、系统配置、地区数据等通用功能的API接口
* @author 系统开发团队
* @version 2.0.0
* @since 1.0.0
*
* @description
* 本模块包含以下功能分组:
* - 文件上传相关API图片上传、文件上传、批量上传
* - 云存储相关API七牛云、阿里云OSS配置获取
* - 系统信息相关API系统配置、版本信息、更新检查
* - 基础数据相关API地区数据、反馈提交
*
* @example
* // 基本用法示例
* import { uploadImage, getSystemConfig } from '@/http/api/common.js'
*
* // 上传图片
* const result = await uploadImage({ filePath: 'path/to/image.jpg' })
*
* // 获取系统配置
* const config = await getSystemConfig()
*/
// ==================== 类型定义 ====================
/**
* @typedef {Object} UploadData 上传数据对象
* @property {string} filePath 文件路径
* @property {string} [name] 文件字段名,默认'file'
* @property {Object} [formData] 额外的表单数据
*/
/**
* @typedef {Object} UploadResult 上传结果对象
* @property {string} url 文件访问URL
* @property {string} key 文件存储键名
* @property {number} size 文件大小
* @property {string} type 文件类型
*/
/**
* @typedef {Object} SystemConfig 系统配置对象
* @property {Object} upload 上传配置
* @property {Object} app 应用配置
* @property {Object} features 功能开关配置
*/
// ==================== 配置常量 ====================
/**
* 通用API的默认配置模板
*/
const COMMON_CONFIG_TEMPLATES = {
// 需要认证的上传请求
AUTHENTICATED_UPLOAD: {
auth: true,
loading: true,
toast: true
},
// 公开的下载请求
PUBLIC_DOWNLOAD: {
auth: false,
loading: true,
toast: true
},
// 静默的配置获取请求
SILENT_CONFIG: {
auth: false,
loading: false,
toast: false
},
// 需要认证的提交请求
AUTHENTICATED_SUBMIT: {
auth: true,
loading: true,
toast: true
}
}
/**
* 通用操作的loading文本配置
*/
const COMMON_LOADING_TEXTS = {
UPLOAD_IMAGE: '正在上传图片...',
UPLOAD_FILE: '正在上传文件...',
UPLOAD_IMAGES: '正在批量上传...',
DOWNLOAD_FILE: '正在下载文件...',
CHECK_UPDATE: '正在检查更新...',
SUBMIT_FEEDBACK: '正在提交反馈...'
}
// ==================== 工具函数 ====================
/**
* 创建通用请求的标准化配置
* @param {string} template 配置模板名称
* @param {Object} customConfig 自定义配置
* @param {string} loadingText 自定义loading文本
* @returns {Object} 标准化的请求配置
*/
const createCommonConfig = (template, customConfig = {}, loadingText = null) => {
const baseConfig = COMMON_CONFIG_TEMPLATES[template] || {}
const config = {
custom: {
...baseConfig,
...(loadingText && { loadingText }),
...customConfig.custom
},
...customConfig
}
// 移除custom属性中的undefined值
Object.keys(config.custom).forEach(key => {
if (config.custom[key] === undefined) {
delete config.custom[key]
}
})
return config
}
/**
* 执行上传请求的通用方法
* @param {string} url 上传URL
* @param {Object} uploadData 上传数据
* @param {string} loadingText loading文本
* @param {Object} config 自定义配置
* @returns {Promise} 请求Promise
*/
const executeUploadRequest = (url, uploadData, loadingText, config = {}) => {
const requestConfig = createCommonConfig('AUTHENTICATED_UPLOAD', config, loadingText)
return uni.$u.http.upload(url, {
filePath: uploadData.filePath,
name: uploadData.name || 'file',
formData: uploadData.formData || {},
...requestConfig
})
}
// ==================== API方法 ====================
// ==================== 文件上传相关API ====================
/**
* 上传单张图片
* @description 上传图片文件到服务器,支持多种图片格式
* @param {UploadData} imageData 图片上传数据对象
* @param {string} imageData.filePath 图片文件路径
* @param {string} [imageData.name='file'] 上传字段名
* @param {Object} [imageData.formData={}] 额外的表单数据
* @param {Object} [config={}] 自定义请求配置
* @returns {Promise<UploadResult>} 返回上传结果包含图片URL等信息
* @example
* // 基本图片上传
* const result = await uploadImage({
* filePath: 'path/to/image.jpg'
* })
*
* // 带额外数据的图片上传
* const result = await uploadImage({
* filePath: 'path/to/image.jpg',
* name: 'avatar',
* formData: { category: 'profile' }
* })
*/
export const uploadImage = (imageData, config = {}) => {
return executeUploadRequest('/upload/image', imageData, COMMON_LOADING_TEXTS.UPLOAD_IMAGE, config)
}
/**
* 批量上传多张图片
* @description 同时上传多张图片,支持并发上传提升效率
* @param {UploadData[]} imageList 图片列表数组
* @param {Object} [config={}] 自定义请求配置
* @param {boolean} [config.showProgress=true] 是否显示整体进度
* @param {number} [config.maxConcurrent=3] 最大并发上传数量
* @returns {Promise<UploadResult[]>} 返回所有图片的上传结果数组
* @example
* // 批量上传图片
* const results = await uploadImages([
* { filePath: 'path/to/image1.jpg' },
* { filePath: 'path/to/image2.jpg' },
* { filePath: 'path/to/image3.jpg' }
* ])
*
* // 自定义并发数量
* const results = await uploadImages(imageList, {
* maxConcurrent: 5,
* custom: { loadingText: '正在批量上传图片...' }
* })
*/
export const uploadImages = async (imageList, config = {}) => {
const { maxConcurrent = 3, showProgress = true } = config
// 显示整体进度loading
if (showProgress) {
uni.showLoading({
title: config.custom?.loadingText || COMMON_LOADING_TEXTS.UPLOAD_IMAGES
})
}
try {
// 分批并发上传
const results = []
for (let i = 0; i < imageList.length; i += maxConcurrent) {
const batch = imageList.slice(i, i + maxConcurrent)
const batchPromises = batch.map(imageData => {
return uploadImage(imageData, {
...config,
custom: {
loading: false, // 批量上传时不显示单个loading
...config.custom
}
})
})
const batchResults = await Promise.all(batchPromises)
results.push(...batchResults)
}
return results
} finally {
if (showProgress) {
uni.hideLoading()
}
}
}
/**
* 上传通用文件
* @description 上传各种类型的文件到服务器
* @param {UploadData} fileData 文件上传数据对象
* @param {string} fileData.filePath 文件路径
* @param {string} [fileData.name='file'] 上传字段名
* @param {Object} [fileData.formData={}] 额外的表单数据
* @param {Object} [config={}] 自定义请求配置
* @returns {Promise<UploadResult>} 返回上传结果包含文件URL等信息
* @example
* // 上传文档文件
* const result = await uploadFile({
* filePath: 'path/to/document.pdf',
* formData: { type: 'document' }
* })
*/
export const uploadFile = (fileData, config = {}) => {
return executeUploadRequest('/upload/file', fileData, COMMON_LOADING_TEXTS.UPLOAD_FILE, config)
}
/**
* 下载文件到本地
* @description 从服务器下载文件到本地存储
* @param {string} url 文件下载URL
* @param {Object} [config={}] 自定义请求配置
* @param {string} [config.savePath] 保存路径,不指定则使用默认路径
* @returns {Promise<Object>} 返回下载结果,包含本地文件路径
* @example
* // 基本文件下载
* const result = await downloadFile('https://example.com/file.pdf')
*
* // 指定保存路径
* const result = await downloadFile('https://example.com/file.pdf', {
* savePath: 'downloads/myfile.pdf'
* })
*/
export const downloadFile = (url, config = {}) => {
const requestConfig = createCommonConfig('PUBLIC_DOWNLOAD', config, COMMON_LOADING_TEXTS.DOWNLOAD_FILE)
return uni.$u.http.download(url, {
...(config.savePath && { savePath: config.savePath }),
...requestConfig
})
}
// ==================== 云存储相关API ====================
/**
* 获取七牛云上传凭证
* @description 获取七牛云直传所需的上传token
* @param {Object} [params={}] 请求参数
* @param {string} [params.bucket] 存储桶名称
* @param {string} [params.prefix] 文件前缀
* @param {number} [params.expires] 过期时间(秒)
* @param {Object} [config={}] 自定义请求配置
* @returns {Promise<Object>} 返回七牛云上传配置信息
* @example
* // 获取默认配置
* const qiniuConfig = await getQiniuToken()
*
* // 获取指定桶的配置
* const qiniuConfig = await getQiniuToken({
* bucket: 'my-bucket',
* prefix: 'images/',
* expires: 3600
* })
*/
export const getQiniuToken = (params = {}, config = {}) => {
const requestConfig = createCommonConfig('SILENT_CONFIG', config)
return uni.$u.http.get('/upload/qiniu-token', {
...(Object.keys(params).length > 0 && { params }),
...requestConfig
})
}
/**
* 获取阿里云OSS上传签名
* @description 获取阿里云OSS直传所需的签名信息
* @param {Object} [params={}] 请求参数
* @param {string} [params.bucket] 存储桶名称
* @param {string} [params.prefix] 文件前缀
* @param {number} [params.expires] 过期时间(秒)
* @param {Object} [config={}] 自定义请求配置
* @returns {Promise<Object>} 返回OSS上传配置信息
* @example
* // 获取默认OSS配置
* const ossConfig = await getOSSSignature()
*
* // 获取指定配置
* const ossConfig = await getOSSSignature({
* bucket: 'my-oss-bucket',
* prefix: 'uploads/',
* expires: 1800
* })
*/
export const getOSSSignature = (params = {}, config = {}) => {
const requestConfig = createCommonConfig('SILENT_CONFIG', config)
return uni.$u.http.get('/upload/oss-signature', {
...(Object.keys(params).length > 0 && { params }),
...requestConfig
})
}
// ==================== 系统信息相关API ====================
/**
* 获取系统配置信息
* @description 获取应用的系统配置,包括功能开关、上传配置等
* @param {Object} [params={}] 查询参数
* @param {string[]} [params.keys] 指定获取的配置键名数组
* @param {string} [params.category] 配置分类:'app' | 'upload' | 'features'
* @param {Object} [config={}] 自定义请求配置
* @returns {Promise<SystemConfig>} 返回系统配置对象
* @example
* // 获取所有配置
* const systemConfig = await getSystemConfig()
*
* // 获取指定分类的配置
* const uploadConfig = await getSystemConfig({
* category: 'upload'
* })
*
* // 获取指定键的配置
* const specificConfig = await getSystemConfig({
* keys: ['maxFileSize', 'allowedTypes']
* })
*/
export const getSystemConfig = (params = {}, config = {}) => {
const requestConfig = createCommonConfig('SILENT_CONFIG', config)
return uni.$u.http.get('/system/config', {
...(Object.keys(params).length > 0 && { params }),
...requestConfig
})
}
/**
* 获取应用版本信息
* @description 获取当前应用的版本信息和更新历史
* @param {Object} [config={}] 自定义请求配置
* @returns {Promise<Object>} 返回版本信息对象
* @example
* // 获取版本信息
* const versionInfo = await getVersionInfo()
* // 返回格式:
* // {
* // currentVersion: '1.0.0',
* // latestVersion: '1.1.0',
* // updateAvailable: true,
* // updateLog: ['修复bug', '新增功能']
* // }
*/
export const getVersionInfo = (config = {}) => {
const requestConfig = createCommonConfig('SILENT_CONFIG', config)
return uni.$u.http.get('/system/version', requestConfig)
}
/**
* 检查应用更新
* @description 检查是否有新版本可用,并获取更新信息
* @param {Object} versionData 当前版本数据
* @param {string} versionData.currentVersion 当前版本号
* @param {string} versionData.platform 平台:'android' | 'ios' | 'h5' | 'mp-weixin'
* @param {string} [versionData.channel] 更新渠道
* @param {Object} [config={}] 自定义请求配置
* @returns {Promise<Object>} 返回更新检查结果
* @example
* // 检查更新
* const updateInfo = await checkUpdate({
* currentVersion: '1.0.0',
* platform: 'android'
* })
*
* // 指定更新渠道
* const updateInfo = await checkUpdate({
* currentVersion: '1.0.0',
* platform: 'android',
* channel: 'beta'
* })
*/
export const checkUpdate = (versionData, config = {}) => {
const requestConfig = createCommonConfig('PUBLIC_DOWNLOAD', config, COMMON_LOADING_TEXTS.CHECK_UPDATE)
return uni.$u.http.post('/system/check-update', versionData, requestConfig)
}
// 短信验证码相关API已移至 http/api/auth.js 文件中
// ==================== 基础数据相关API ====================
/**
* 获取地区数据
* @description 获取省市区三级联动的地区数据
* @param {Object} [params={}] 查询参数
* @param {string} [params.level] 数据层级:'province' | 'city' | 'district' | 'all'
* @param {string} [params.parentCode] 父级地区代码
* @param {boolean} [params.includeCoordinates] 是否包含经纬度信息
* @param {Object} [config={}] 自定义请求配置
* @returns {Promise<Object[]>} 返回地区数据数组
* @example
* // 获取所有省份
* const provinces = await getRegionData({ level: 'province' })
*
* // 获取指定省份下的城市
* const cities = await getRegionData({
* level: 'city',
* parentCode: '110000'
* })
*
* // 获取完整的三级数据
* const allRegions = await getRegionData({ level: 'all' })
*/
export const getRegionData = (params = {}, config = {}) => {
const requestConfig = createCommonConfig('SILENT_CONFIG', config)
return uni.$u.http.get('/common/regions', {
...(Object.keys(params).length > 0 && { params }),
...requestConfig
})
}
/**
* 提交用户反馈
* @description 提交用户的意见反馈或问题报告
* @param {Object} feedbackData 反馈数据对象
* @param {string} feedbackData.type 反馈类型:'bug' | 'suggestion' | 'complaint' | 'other'
* @param {string} feedbackData.title 反馈标题
* @param {string} feedbackData.content 反馈内容
* @param {string} [feedbackData.contact] 联系方式
* @param {string[]} [feedbackData.images] 相关图片URL数组
* @param {Object} [feedbackData.deviceInfo] 设备信息
* @param {Object} [config={}] 自定义请求配置
* @returns {Promise<Object>} 返回提交结果包含反馈ID
* @example
* // 提交bug反馈
* const result = await submitFeedback({
* type: 'bug',
* title: '登录页面异常',
* content: '点击登录按钮后页面卡死',
* contact: 'user@example.com',
* images: ['https://example.com/screenshot.jpg']
* })
*
* // 提交功能建议
* const result = await submitFeedback({
* type: 'suggestion',
* title: '希望增加夜间模式',
* content: '建议应用支持夜间模式,保护用户视力'
* })
*/
export const submitFeedback = (feedbackData, config = {}) => {
const requestConfig = createCommonConfig('AUTHENTICATED_SUBMIT', config, COMMON_LOADING_TEXTS.SUBMIT_FEEDBACK)
return uni.$u.http.post('/feedback', feedbackData, requestConfig)
}
// ==================== 导出配置常量(供外部使用) ====================
/**
* 导出通用配置常量,供其他模块使用
*/
export const COMMON_CONFIG = {
COMMON_CONFIG_TEMPLATES,
COMMON_LOADING_TEXTS
}
/**
* 导出通用工具函数,供其他模块使用
*/
export const COMMON_UTILS = {
createCommonConfig,
executeUploadRequest
}