Generating commit message...
This commit is contained in:
87
mini-program/api/config.js
Normal file
87
mini-program/api/config.js
Normal file
@@ -0,0 +1,87 @@
|
||||
// API基础配置
|
||||
const config = {
|
||||
// 开发环境
|
||||
development: {
|
||||
baseURL: 'http://localhost:3000/api',
|
||||
timeout: 10000
|
||||
},
|
||||
// 生产环境
|
||||
production: {
|
||||
baseURL: 'https://api.jiebanke.com/api',
|
||||
timeout: 15000
|
||||
}
|
||||
}
|
||||
|
||||
// 获取当前环境配置
|
||||
const getConfig = () => {
|
||||
const env = process.env.NODE_ENV || 'development'
|
||||
return config[env]
|
||||
}
|
||||
|
||||
// API端点
|
||||
const endpoints = {
|
||||
// 用户相关
|
||||
USER: {
|
||||
LOGIN: '/auth/login',
|
||||
REGISTER: '/auth/register',
|
||||
PROFILE: '/user/profile',
|
||||
UPDATE_PROFILE: '/user/profile',
|
||||
UPLOAD_AVATAR: '/user/avatar'
|
||||
},
|
||||
|
||||
// 旅行计划
|
||||
TRAVEL: {
|
||||
LIST: '/travel/list',
|
||||
DETAIL: '/travel/detail',
|
||||
CREATE: '/travel/create',
|
||||
JOIN: '/travel/join',
|
||||
MY_PLANS: '/travel/my-plans',
|
||||
SEARCH: '/travel/search'
|
||||
},
|
||||
|
||||
// 动物认养
|
||||
ANIMAL: {
|
||||
LIST: '/animal/list',
|
||||
DETAIL: '/animal/detail',
|
||||
ADOPT: '/animal/adopt',
|
||||
MY_ANIMALS: '/animal/my-animals',
|
||||
CATEGORIES: '/animal/categories'
|
||||
},
|
||||
|
||||
// 送花服务
|
||||
FLOWER: {
|
||||
LIST: '/flower/list',
|
||||
DETAIL: '/flower/detail',
|
||||
ORDER: '/flower/order',
|
||||
MY_ORDERS: '/flower/my-orders',
|
||||
CATEGORIES: '/flower/categories'
|
||||
},
|
||||
|
||||
// 订单管理
|
||||
ORDER: {
|
||||
LIST: '/order/list',
|
||||
DETAIL: '/order/detail',
|
||||
CANCEL: '/order/cancel',
|
||||
PAY: '/order/pay',
|
||||
CONFIRM: '/order/confirm'
|
||||
},
|
||||
|
||||
// 支付相关
|
||||
PAYMENT: {
|
||||
CREATE: '/payment/create',
|
||||
QUERY: '/payment/query',
|
||||
REFUND: '/payment/refund'
|
||||
},
|
||||
|
||||
// 系统相关
|
||||
SYSTEM: {
|
||||
CONFIG: '/system/config',
|
||||
NOTICE: '/system/notice',
|
||||
FEEDBACK: '/system/feedback'
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
...getConfig(),
|
||||
endpoints
|
||||
}
|
||||
169
mini-program/api/example.js
Normal file
169
mini-program/api/example.js
Normal file
@@ -0,0 +1,169 @@
|
||||
// API 使用示例
|
||||
import api, { userService, travelService, homeService, apiUtils } from './index.js'
|
||||
|
||||
// 示例1: 用户登录
|
||||
async function exampleLogin() {
|
||||
try {
|
||||
const result = await userService.login({
|
||||
username: 'user123',
|
||||
password: 'password123'
|
||||
})
|
||||
|
||||
console.log('登录成功:', result)
|
||||
// 保存token
|
||||
api.setAuthToken(result.token)
|
||||
|
||||
} catch (error) {
|
||||
console.error('登录失败:', error)
|
||||
api.handleError(error)
|
||||
}
|
||||
}
|
||||
|
||||
// 示例2: 获取首页数据
|
||||
async function exampleGetHomeData() {
|
||||
try {
|
||||
const homeData = await homeService.getHomeData()
|
||||
console.log('首页数据:', homeData)
|
||||
|
||||
// 或者使用错误处理包装器
|
||||
const { success, data, error } = await api.withErrorHandling(
|
||||
homeService.getHomeData(),
|
||||
'首页数据加载成功'
|
||||
)
|
||||
|
||||
if (success) {
|
||||
// 处理数据
|
||||
console.log('处理首页数据:', data)
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
api.handleError(error, '首页数据加载失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 示例3: 分页获取旅行计划
|
||||
async function exampleGetTravelPlans() {
|
||||
try {
|
||||
const pagination = apiUtils.generatePagination(1, 10)
|
||||
const travels = await travelService.getList({
|
||||
...pagination,
|
||||
keyword: '西藏'
|
||||
})
|
||||
|
||||
console.log('旅行计划列表:', travels)
|
||||
|
||||
} catch (error) {
|
||||
api.handleError(error)
|
||||
}
|
||||
}
|
||||
|
||||
// 示例4: 文件上传
|
||||
async function exampleUploadAvatar() {
|
||||
try {
|
||||
// 选择图片
|
||||
const res = await uni.chooseImage({
|
||||
count: 1,
|
||||
sizeType: ['compressed'],
|
||||
sourceType: ['album']
|
||||
})
|
||||
|
||||
const filePath = res.tempFilePaths[0]
|
||||
const uploadResult = await userService.uploadAvatar(filePath)
|
||||
|
||||
console.log('头像上传成功:', uploadResult)
|
||||
|
||||
} catch (error) {
|
||||
api.handleError(error, '头像上传失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 示例5: 完整的页面数据加载流程
|
||||
async function loadPageData() {
|
||||
try {
|
||||
// 并行加载多个数据
|
||||
const [banners, travels, animals, flowers] = await Promise.all([
|
||||
homeService.getBanners(),
|
||||
homeService.getRecommendedTravels(),
|
||||
homeService.getHotAnimals(),
|
||||
homeService.getFeaturedFlowers()
|
||||
])
|
||||
|
||||
return {
|
||||
banners: banners || [],
|
||||
travelPlans: travels || [],
|
||||
animals: animals || [],
|
||||
flowers: flowers || []
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
api.handleError(error)
|
||||
// 返回默认数据或空数据
|
||||
return {
|
||||
banners: [],
|
||||
travelPlans: [],
|
||||
animals: [],
|
||||
flowers: []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 示例6: 订单支付流程
|
||||
async function examplePaymentFlow(orderId) {
|
||||
try {
|
||||
// 1. 创建支付
|
||||
const payment = await paymentService.create({
|
||||
orderId,
|
||||
amount: 100,
|
||||
paymentMethod: 'wechat'
|
||||
})
|
||||
|
||||
// 2. 调用微信支付
|
||||
const payResult = await uni.requestPayment({
|
||||
timeStamp: payment.timeStamp,
|
||||
nonceStr: payment.nonceStr,
|
||||
package: payment.package,
|
||||
signType: payment.signType,
|
||||
paySign: payment.paySign
|
||||
})
|
||||
|
||||
// 3. 确认支付结果
|
||||
if (payResult.errMsg === 'requestPayment:ok') {
|
||||
// 支付成功,更新订单状态
|
||||
await orderService.pay(orderId)
|
||||
console.log('支付成功')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
api.handleError(error, '支付失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 导出示例函数
|
||||
export default {
|
||||
exampleLogin,
|
||||
exampleGetHomeData,
|
||||
exampleGetTravelPlans,
|
||||
exampleUploadAvatar,
|
||||
loadPageData,
|
||||
examplePaymentFlow
|
||||
}
|
||||
|
||||
// 在页面中使用示例
|
||||
/*
|
||||
// 在Vue组件的methods中
|
||||
methods: {
|
||||
async loadData() {
|
||||
const pageData = await loadPageData()
|
||||
this.banners = pageData.banners
|
||||
this.travelPlans = pageData.travelPlans
|
||||
this.animals = pageData.animals
|
||||
this.flowers = pageData.flowers
|
||||
},
|
||||
|
||||
async handleLogin() {
|
||||
await exampleLogin()
|
||||
// 登录成功后重新加载数据
|
||||
await this.loadData()
|
||||
}
|
||||
}
|
||||
*/
|
||||
99
mini-program/api/index.js
Normal file
99
mini-program/api/index.js
Normal file
@@ -0,0 +1,99 @@
|
||||
// API模块主入口
|
||||
import request from './request.js'
|
||||
import * as services from './services.js'
|
||||
|
||||
// 导出所有服务
|
||||
export * from './services.js'
|
||||
|
||||
// 导出请求实例
|
||||
export { request }
|
||||
|
||||
// 默认导出
|
||||
export default {
|
||||
// 请求实例
|
||||
request,
|
||||
|
||||
// 所有服务
|
||||
...services,
|
||||
|
||||
// 工具函数
|
||||
utils: services.apiUtils,
|
||||
|
||||
// 初始化配置
|
||||
init(config = {}) {
|
||||
// 可以在这里进行一些初始化配置
|
||||
console.log('API模块初始化完成', config)
|
||||
},
|
||||
|
||||
// 设置认证token
|
||||
setAuthToken(token) {
|
||||
uni.setStorageSync('token', token)
|
||||
},
|
||||
|
||||
// 获取认证token
|
||||
getAuthToken() {
|
||||
return uni.getStorageSync('token')
|
||||
},
|
||||
|
||||
// 清除认证信息
|
||||
clearAuth() {
|
||||
uni.removeStorageSync('token')
|
||||
uni.removeStorageSync('refreshToken')
|
||||
},
|
||||
|
||||
// 检查是否已登录
|
||||
isLoggedIn() {
|
||||
return !!this.getAuthToken()
|
||||
},
|
||||
|
||||
// 统一错误处理
|
||||
handleError(error, defaultMessage = '操作失败') {
|
||||
const errorMessage = error.message || defaultMessage
|
||||
const errorCode = error.code || 'UNKNOWN_ERROR'
|
||||
|
||||
// 可以根据错误码进行不同的处理
|
||||
switch (errorCode) {
|
||||
case 'UNAUTHORIZED':
|
||||
this.clearAuth()
|
||||
uni.navigateTo({ url: '/pages/auth/login' })
|
||||
break
|
||||
case 'NETWORK_ERROR':
|
||||
uni.showToast({ title: '网络连接失败', icon: 'none' })
|
||||
break
|
||||
default:
|
||||
uni.showToast({ title: errorMessage, icon: 'none' })
|
||||
}
|
||||
|
||||
return { error: true, code: errorCode, message: errorMessage }
|
||||
},
|
||||
|
||||
// 请求包装器,自动处理错误
|
||||
async withErrorHandling(promise, successMessage = '操作成功') {
|
||||
try {
|
||||
const result = await promise
|
||||
if (successMessage) {
|
||||
uni.showToast({ title: successMessage, icon: 'success' })
|
||||
}
|
||||
return { success: true, data: result }
|
||||
} catch (error) {
|
||||
return this.handleError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 自动初始化
|
||||
const api = {
|
||||
request,
|
||||
...services
|
||||
}
|
||||
|
||||
// 全局错误处理
|
||||
const originalRequest = uni.request
|
||||
uni.request = function(config) {
|
||||
return originalRequest.call(this, config).catch(error => {
|
||||
console.error('请求失败:', error)
|
||||
throw error
|
||||
})
|
||||
}
|
||||
|
||||
export default api
|
||||
312
mini-program/api/mock.js
Normal file
312
mini-program/api/mock.js
Normal file
@@ -0,0 +1,312 @@
|
||||
// Mock数据 - 用于开发和测试
|
||||
import { OrderStatus, TravelStatus } from './types.js'
|
||||
|
||||
// Mock用户数据
|
||||
export const mockUsers = [
|
||||
{
|
||||
id: 1,
|
||||
username: 'user1',
|
||||
nickname: '旅行爱好者',
|
||||
avatar: '/static/user/avatar1.jpg',
|
||||
phone: '138****1234',
|
||||
points: 150,
|
||||
level: 2,
|
||||
createTime: '2024-01-15'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
username: 'user2',
|
||||
nickname: '动物保护者',
|
||||
avatar: '/static/user/avatar2.jpg',
|
||||
email: 'user2@example.com',
|
||||
points: 300,
|
||||
level: 3,
|
||||
createTime: '2024-02-20'
|
||||
}
|
||||
]
|
||||
|
||||
// Mock轮播图数据
|
||||
export const mockBanners = [
|
||||
{
|
||||
id: 1,
|
||||
image: '/static/banners/banner1.jpg',
|
||||
title: '西藏之旅',
|
||||
link: '/pages/travel/list',
|
||||
type: 'travel'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
image: '/static/banners/banner2.jpg',
|
||||
title: '动物认养',
|
||||
link: '/pages/animal/list',
|
||||
type: 'animal'
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
image: '/static/banners/banner3.jpg',
|
||||
title: '鲜花配送',
|
||||
link: '/pages/flower/list',
|
||||
type: 'flower'
|
||||
}
|
||||
]
|
||||
|
||||
// Mock旅行计划数据
|
||||
export const mockTravelPlans = [
|
||||
{
|
||||
id: 1,
|
||||
title: '西藏拉萨深度游',
|
||||
destination: '西藏拉萨',
|
||||
coverImage: '/static/travel/tibet.jpg',
|
||||
startDate: '2024-10-01',
|
||||
endDate: '2024-10-07',
|
||||
budget: 5000,
|
||||
currentMembers: 3,
|
||||
maxMembers: 6,
|
||||
description: '探索西藏神秘文化,感受高原风情',
|
||||
status: TravelStatus.RECRUITING,
|
||||
creator: mockUsers[0],
|
||||
createTime: '2024-08-20'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: '云南大理休闲游',
|
||||
destination: '云南大理',
|
||||
coverImage: '/static/travel/yunnan.jpg',
|
||||
startDate: '2024-10-05',
|
||||
endDate: '2024-10-12',
|
||||
budget: 3500,
|
||||
currentMembers: 2,
|
||||
maxMembers: 4,
|
||||
description: '漫步古城,享受洱海风光',
|
||||
status: TravelStatus.RECRUITING,
|
||||
creator: mockUsers[1],
|
||||
createTime: '2024-08-22'
|
||||
}
|
||||
]
|
||||
|
||||
// Mock动物数据
|
||||
export const mockAnimals = [
|
||||
{
|
||||
id: 1,
|
||||
name: '小羊驼',
|
||||
species: '羊驼',
|
||||
price: 1000,
|
||||
image: '/static/animals/alpaca.jpg',
|
||||
description: '温顺可爱的羊驼,适合家庭认养',
|
||||
location: '西藏牧场',
|
||||
isHot: true,
|
||||
status: 'available',
|
||||
createTime: '2024-08-15'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: '小绵羊',
|
||||
species: '绵羊',
|
||||
price: 800,
|
||||
image: '/static/animals/sheep.jpg',
|
||||
description: '毛茸茸的小绵羊,非常温顺',
|
||||
location: '内蒙古草原',
|
||||
isHot: false,
|
||||
status: 'available',
|
||||
createTime: '2024-08-18'
|
||||
}
|
||||
]
|
||||
|
||||
// Mock花束数据
|
||||
export const mockFlowers = [
|
||||
{
|
||||
id: 1,
|
||||
name: '浪漫玫瑰',
|
||||
description: '11朵红玫瑰,象征热烈的爱情',
|
||||
price: 199,
|
||||
image: '/static/flowers/rose.jpg',
|
||||
category: '爱情',
|
||||
stock: 50,
|
||||
createTime: '2024-08-10'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: '向日葵花束',
|
||||
description: '9朵向日葵,象征阳光和希望',
|
||||
price: 179,
|
||||
image: '/static/flowers/sunflower.jpg',
|
||||
category: '祝福',
|
||||
stock: 30,
|
||||
createTime: '2024-08-12'
|
||||
}
|
||||
]
|
||||
|
||||
// Mock订单数据
|
||||
export const mockOrders = [
|
||||
{
|
||||
id: 'ORD202408270001',
|
||||
orderNo: '202408270001',
|
||||
type: 'travel',
|
||||
title: '西藏拉萨深度游',
|
||||
image: '/static/travel/tibet.jpg',
|
||||
price: 5000,
|
||||
count: 1,
|
||||
totalAmount: 5000,
|
||||
status: OrderStatus.UNPAID,
|
||||
createTime: '2024-08-27 10:00:00'
|
||||
},
|
||||
{
|
||||
id: 'ORD202408270002',
|
||||
orderNo: '202408270002',
|
||||
type: 'animal',
|
||||
title: '小羊驼认养',
|
||||
image: '/static/animals/alpaca.jpg',
|
||||
price: 1000,
|
||||
count: 1,
|
||||
totalAmount: 1000,
|
||||
status: OrderStatus.PAID,
|
||||
createTime: '2024-08-27 11:30:00',
|
||||
payTime: '2024-08-27 11:35:00'
|
||||
}
|
||||
]
|
||||
|
||||
// Mock系统公告
|
||||
export const mockNotices = [
|
||||
{
|
||||
id: 1,
|
||||
title: '系统维护通知',
|
||||
content: '系统将于今晚进行维护,预计耗时2小时',
|
||||
type: 'system',
|
||||
isActive: true,
|
||||
createTime: '2024-08-26'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: '新功能上线',
|
||||
content: '送花服务正式上线,欢迎体验',
|
||||
type: 'feature',
|
||||
isActive: true,
|
||||
createTime: '2024-08-27'
|
||||
}
|
||||
]
|
||||
|
||||
// Mock API响应
|
||||
export const mockResponses = {
|
||||
// 成功响应
|
||||
success: (data, message = '操作成功') => ({
|
||||
code: 0,
|
||||
message,
|
||||
data,
|
||||
timestamp: Date.now()
|
||||
}),
|
||||
|
||||
// 错误响应
|
||||
error: (code, message) => ({
|
||||
code,
|
||||
message,
|
||||
timestamp: Date.now()
|
||||
}),
|
||||
|
||||
// 分页响应
|
||||
pagination: (list, total, page = 1, pageSize = 10) => ({
|
||||
code: 0,
|
||||
message: '操作成功',
|
||||
data: {
|
||||
list,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
totalPages: Math.ceil(total / pageSize)
|
||||
},
|
||||
timestamp: Date.now()
|
||||
})
|
||||
}
|
||||
|
||||
// Mock服务函数
|
||||
export const mockService = {
|
||||
// 模拟延迟
|
||||
delay: (ms = 500) => new Promise(resolve => setTimeout(resolve, ms)),
|
||||
|
||||
// 模拟登录
|
||||
mockLogin: async (username, password) => {
|
||||
await mockService.delay(1000)
|
||||
|
||||
if (username === 'admin' && password === '123456') {
|
||||
return mockResponses.success({
|
||||
token: 'mock-token-123456',
|
||||
refreshToken: 'mock-refresh-token-123456',
|
||||
userInfo: mockUsers[0]
|
||||
})
|
||||
}
|
||||
|
||||
return mockResponses.error(1001, '用户名或密码错误')
|
||||
},
|
||||
|
||||
// 模拟获取首页数据
|
||||
mockHomeData: async () => {
|
||||
await mockService.delay(800)
|
||||
return mockResponses.success({
|
||||
banners: mockBanners,
|
||||
travelPlans: mockTravelPlans,
|
||||
animals: mockAnimals,
|
||||
flowers: mockFlowers,
|
||||
notices: mockNotices
|
||||
})
|
||||
},
|
||||
|
||||
// 模拟获取列表数据
|
||||
mockList: async (type, page = 1, pageSize = 10) => {
|
||||
await mockService.delay(600)
|
||||
|
||||
const allData = {
|
||||
travel: mockTravelPlans,
|
||||
animal: mockAnimals,
|
||||
flower: mockFlowers,
|
||||
order: mockOrders
|
||||
}
|
||||
|
||||
const data = allData[type] || []
|
||||
const start = (page - 1) * pageSize
|
||||
const end = start + pageSize
|
||||
const paginatedData = data.slice(start, end)
|
||||
|
||||
return mockResponses.pagination(paginatedData, data.length, page, pageSize)
|
||||
},
|
||||
|
||||
// 模拟获取详情
|
||||
mockDetail: async (type, id) => {
|
||||
await mockService.delay(500)
|
||||
|
||||
const allData = {
|
||||
travel: mockTravelPlans,
|
||||
animal: mockAnimals,
|
||||
flower: mockFlowers,
|
||||
order: mockOrders
|
||||
}
|
||||
|
||||
const data = allData[type] || []
|
||||
const item = data.find(item => item.id === id || item.id === parseInt(id))
|
||||
|
||||
if (item) {
|
||||
return mockResponses.success(item)
|
||||
}
|
||||
|
||||
return mockResponses.error(404, '数据不存在')
|
||||
}
|
||||
}
|
||||
|
||||
// 导出所有Mock数据
|
||||
export default {
|
||||
mockUsers,
|
||||
mockBanners,
|
||||
mockTravelPlans,
|
||||
mockAnimals,
|
||||
mockFlowers,
|
||||
mockOrders,
|
||||
mockNotices,
|
||||
mockResponses,
|
||||
mockService
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
/*
|
||||
// 在开发环境中使用Mock数据
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
// 可以在这里替换真实的API调用
|
||||
}
|
||||
*/
|
||||
230
mini-program/api/request.js
Normal file
230
mini-program/api/request.js
Normal file
@@ -0,0 +1,230 @@
|
||||
import config from './config.js'
|
||||
|
||||
// 请求队列(用于处理token刷新)
|
||||
const requestQueue = []
|
||||
let isRefreshing = false
|
||||
|
||||
class Request {
|
||||
constructor() {
|
||||
this.baseURL = config.baseURL
|
||||
this.timeout = config.timeout
|
||||
this.interceptors = {
|
||||
request: [],
|
||||
response: []
|
||||
}
|
||||
}
|
||||
|
||||
// 添加请求拦截器
|
||||
addRequestInterceptor(interceptor) {
|
||||
this.interceptors.request.push(interceptor)
|
||||
}
|
||||
|
||||
// 添加响应拦截器
|
||||
addResponseInterceptor(interceptor) {
|
||||
this.interceptors.response.push(interceptor)
|
||||
}
|
||||
|
||||
// 执行请求拦截器
|
||||
async runRequestInterceptors(config) {
|
||||
for (const interceptor of this.interceptors.request) {
|
||||
config = await interceptor(config)
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
// 执行响应拦截器
|
||||
async runResponseInterceptors(response) {
|
||||
for (const interceptor of this.interceptors.response) {
|
||||
response = await interceptor(response)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
// 核心请求方法
|
||||
async request(options) {
|
||||
try {
|
||||
// 合并配置
|
||||
const requestConfig = {
|
||||
url: options.url.startsWith('http') ? options.url : `${this.baseURL}${options.url}`,
|
||||
method: options.method || 'GET',
|
||||
header: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.header
|
||||
},
|
||||
data: options.data,
|
||||
timeout: this.timeout
|
||||
}
|
||||
|
||||
// 执行请求拦截器
|
||||
const finalConfig = await this.runRequestInterceptors(requestConfig)
|
||||
|
||||
// 发起请求
|
||||
const response = await uni.request(finalConfig)
|
||||
|
||||
// 执行响应拦截器
|
||||
const finalResponse = await this.runResponseInterceptors(response)
|
||||
|
||||
return finalResponse[1] // uni.request返回的是数组[error, success]
|
||||
} catch (error) {
|
||||
console.error('Request error:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// GET请求
|
||||
get(url, data = {}, options = {}) {
|
||||
return this.request({
|
||||
url,
|
||||
method: 'GET',
|
||||
data,
|
||||
...options
|
||||
})
|
||||
}
|
||||
|
||||
// POST请求
|
||||
post(url, data = {}, options = {}) {
|
||||
return this.request({
|
||||
url,
|
||||
method: 'POST',
|
||||
data,
|
||||
...options
|
||||
})
|
||||
}
|
||||
|
||||
// PUT请求
|
||||
put(url, data = {}, options = {}) {
|
||||
return this.request({
|
||||
url,
|
||||
method: 'PUT',
|
||||
data,
|
||||
...options
|
||||
})
|
||||
}
|
||||
|
||||
// DELETE请求
|
||||
delete(url, data = {}, options = {}) {
|
||||
return this.request({
|
||||
url,
|
||||
method: 'DELETE',
|
||||
data,
|
||||
...options
|
||||
})
|
||||
}
|
||||
|
||||
// 上传文件
|
||||
upload(url, filePath, formData = {}, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.uploadFile({
|
||||
url: `${this.baseURL}${url}`,
|
||||
filePath,
|
||||
name: 'file',
|
||||
formData,
|
||||
success: resolve,
|
||||
fail: reject,
|
||||
...options
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 下载文件
|
||||
download(url, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.downloadFile({
|
||||
url: `${this.baseURL}${url}`,
|
||||
success: resolve,
|
||||
fail: reject,
|
||||
...options
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 创建请求实例
|
||||
const request = new Request()
|
||||
|
||||
// 添加请求拦截器 - Token处理
|
||||
request.addRequestInterceptor(async (config) => {
|
||||
const token = uni.getStorageSync('token')
|
||||
if (token) {
|
||||
config.header.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
// 添加响应拦截器 - 错误处理
|
||||
request.addResponseInterceptor(async (response) => {
|
||||
const { statusCode, data } = response
|
||||
|
||||
if (statusCode === 200) {
|
||||
if (data.code === 0) {
|
||||
return data.data
|
||||
} else {
|
||||
// 业务错误
|
||||
const error = new Error(data.message || '业务错误')
|
||||
error.code = data.code
|
||||
throw error
|
||||
}
|
||||
} else if (statusCode === 401) {
|
||||
// Token过期,尝试刷新
|
||||
return handleTokenExpired(response)
|
||||
} else {
|
||||
// 网络错误
|
||||
throw new Error(`网络错误: ${statusCode}`)
|
||||
}
|
||||
})
|
||||
|
||||
// Token过期处理
|
||||
async function handleTokenExpired(response) {
|
||||
if (isRefreshing) {
|
||||
// 如果正在刷新,将请求加入队列
|
||||
return new Promise((resolve) => {
|
||||
requestQueue.push(() => resolve(request.request(response.config)))
|
||||
})
|
||||
}
|
||||
|
||||
isRefreshing = true
|
||||
const refreshToken = uni.getStorageSync('refreshToken')
|
||||
|
||||
if (!refreshToken) {
|
||||
// 没有refreshToken,跳转到登录页
|
||||
uni.navigateTo({ url: '/pages/auth/login' })
|
||||
throw new Error('请重新登录')
|
||||
}
|
||||
|
||||
try {
|
||||
// 尝试刷新Token
|
||||
const result = await request.post(config.endpoints.USER.REFRESH_TOKEN, {
|
||||
refreshToken
|
||||
})
|
||||
|
||||
// 保存新Token
|
||||
uni.setStorageSync('token', result.token)
|
||||
uni.setStorageSync('refreshToken', result.refreshToken)
|
||||
|
||||
// 重试原始请求
|
||||
const retryResponse = await request.request(response.config)
|
||||
|
||||
// 处理队列中的请求
|
||||
processRequestQueue()
|
||||
|
||||
return retryResponse
|
||||
} catch (error) {
|
||||
// 刷新失败,清空Token并跳转登录
|
||||
uni.removeStorageSync('token')
|
||||
uni.removeStorageSync('refreshToken')
|
||||
uni.navigateTo({ url: '/pages/auth/login' })
|
||||
throw error
|
||||
} finally {
|
||||
isRefreshing = false
|
||||
}
|
||||
}
|
||||
|
||||
// 处理请求队列
|
||||
function processRequestQueue() {
|
||||
while (requestQueue.length > 0) {
|
||||
const retry = requestQueue.shift()
|
||||
retry()
|
||||
}
|
||||
}
|
||||
|
||||
export default request
|
||||
189
mini-program/api/services.js
Normal file
189
mini-program/api/services.js
Normal file
@@ -0,0 +1,189 @@
|
||||
import request from './request.js'
|
||||
import config from './config.js'
|
||||
|
||||
const { endpoints } = config
|
||||
|
||||
// 用户服务
|
||||
export const userService = {
|
||||
// 登录
|
||||
login: (data) => request.post(endpoints.USER.LOGIN, data),
|
||||
|
||||
// 注册
|
||||
register: (data) => request.post(endpoints.USER.REGISTER, data),
|
||||
|
||||
// 获取用户信息
|
||||
getProfile: () => request.get(endpoints.USER.PROFILE),
|
||||
|
||||
// 更新用户信息
|
||||
updateProfile: (data) => request.put(endpoints.USER.UPDATE_PROFILE, data),
|
||||
|
||||
// 上传头像
|
||||
uploadAvatar: (filePath) => request.upload(endpoints.USER.UPLOAD_AVATAR, filePath),
|
||||
|
||||
// 退出登录
|
||||
logout: () => {
|
||||
uni.removeStorageSync('token')
|
||||
uni.removeStorageSync('refreshToken')
|
||||
return Promise.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
// 旅行计划服务
|
||||
export const travelService = {
|
||||
// 获取旅行计划列表
|
||||
getList: (params = {}) => request.get(endpoints.TRAVEL.LIST, params),
|
||||
|
||||
// 获取旅行计划详情
|
||||
getDetail: (id) => request.get(`${endpoints.TRAVEL.DETAIL}/${id}`),
|
||||
|
||||
// 创建旅行计划
|
||||
create: (data) => request.post(endpoints.TRAVEL.CREATE, data),
|
||||
|
||||
// 加入旅行计划
|
||||
join: (travelId) => request.post(`${endpoints.TRAVEL.JOIN}/${travelId}`),
|
||||
|
||||
// 获取我的旅行计划
|
||||
getMyPlans: (params = {}) => request.get(endpoints.TRAVEL.MY_PLANS, params),
|
||||
|
||||
// 搜索旅行计划
|
||||
search: (keyword, params = {}) => request.get(endpoints.TRAVEL.SEARCH, { keyword, ...params })
|
||||
}
|
||||
|
||||
// 动物认养服务
|
||||
export const animalService = {
|
||||
// 获取动物列表
|
||||
getList: (params = {}) => request.get(endpoints.ANIMAL.LIST, params),
|
||||
|
||||
// 获取动物详情
|
||||
getDetail: (id) => request.get(`${endpoints.ANIMAL.DETAIL}/${id}`),
|
||||
|
||||
// 认养动物
|
||||
adopt: (animalId, data) => request.post(`${endpoints.ANIMAL.ADOPT}/${animalId}`, data),
|
||||
|
||||
// 获取我的动物
|
||||
getMyAnimals: (params = {}) => request.get(endpoints.ANIMAL.MY_ANIMALS, params),
|
||||
|
||||
// 获取动物分类
|
||||
getCategories: () => request.get(endpoints.ANIMAL.CATEGORIES)
|
||||
}
|
||||
|
||||
// 送花服务
|
||||
export const flowerService = {
|
||||
// 获取花束列表
|
||||
getList: (params = {}) => request.get(endpoints.FLOWER.LIST, params),
|
||||
|
||||
// 获取花束详情
|
||||
getDetail: (id) => request.get(`${endpoints.FLOWER.DETAIL}/${id}`),
|
||||
|
||||
// 下单
|
||||
order: (data) => request.post(endpoints.FLOWER.ORDER, data),
|
||||
|
||||
// 获取我的订单
|
||||
getMyOrders: (params = {}) => request.get(endpoints.FLOWER.MY_ORDERS, params),
|
||||
|
||||
// 获取花束分类
|
||||
getCategories: () => request.get(endpoints.FLOWER.CATEGORIES)
|
||||
}
|
||||
|
||||
// 订单服务
|
||||
export const orderService = {
|
||||
// 获取订单列表
|
||||
getList: (params = {}) => request.get(endpoints.ORDER.LIST, params),
|
||||
|
||||
// 获取订单详情
|
||||
getDetail: (id) => request.get(`${endpoints.ORDER.DETAIL}/${id}`),
|
||||
|
||||
// 取消订单
|
||||
cancel: (id) => request.post(`${endpoints.ORDER.CANCEL}/${id}`),
|
||||
|
||||
// 支付订单
|
||||
pay: (id) => request.post(`${endpoints.ORDER.PAY}/${id}`),
|
||||
|
||||
// 确认收货
|
||||
confirm: (id) => request.post(`${endpoints.ORDER.CONFIRM}/${id}`)
|
||||
}
|
||||
|
||||
// 支付服务
|
||||
export const paymentService = {
|
||||
// 创建支付
|
||||
create: (data) => request.post(endpoints.PAYMENT.CREATE, data),
|
||||
|
||||
// 查询支付状态
|
||||
query: (paymentId) => request.get(`${endpoints.PAYMENT.QUERY}/${paymentId}`),
|
||||
|
||||
// 退款
|
||||
refund: (paymentId, data) => request.post(`${endpoints.PAYMENT.REFUND}/${paymentId}`, data)
|
||||
}
|
||||
|
||||
// 系统服务
|
||||
export const systemService = {
|
||||
// 获取系统配置
|
||||
getConfig: () => request.get(endpoints.SYSTEM.CONFIG),
|
||||
|
||||
// 获取公告列表
|
||||
getNotices: (params = {}) => request.get(endpoints.SYSTEM.NOTICE, params),
|
||||
|
||||
// 提交反馈
|
||||
submitFeedback: (data) => request.post(endpoints.SYSTEM.FEEDBACK, data)
|
||||
}
|
||||
|
||||
// 首页数据服务
|
||||
export const homeService = {
|
||||
// 获取首页数据
|
||||
getHomeData: () => request.get('/home/data'),
|
||||
|
||||
// 获取轮播图
|
||||
getBanners: () => request.get('/home/banners'),
|
||||
|
||||
// 获取推荐旅行计划
|
||||
getRecommendedTravels: () => request.get('/home/recommended-travels'),
|
||||
|
||||
// 获取热门动物
|
||||
getHotAnimals: () => request.get('/home/hot-animals'),
|
||||
|
||||
// 获取精选花束
|
||||
getFeaturedFlowers: () => request.get('/home/featured-flowers')
|
||||
}
|
||||
|
||||
// 工具函数
|
||||
export const apiUtils = {
|
||||
// 生成分页参数
|
||||
generatePagination: (page = 1, pageSize = 10) => ({
|
||||
page,
|
||||
pageSize,
|
||||
skip: (page - 1) * pageSize
|
||||
}),
|
||||
|
||||
// 处理上传进度
|
||||
handleUploadProgress: (progressEvent) => {
|
||||
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
return percent
|
||||
},
|
||||
|
||||
// 处理下载进度
|
||||
handleDownloadProgress: (progressEvent) => {
|
||||
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
return percent
|
||||
},
|
||||
|
||||
// 格式化错误信息
|
||||
formatError: (error) => {
|
||||
if (error.code) {
|
||||
return error.message
|
||||
}
|
||||
return '网络连接失败,请检查网络设置'
|
||||
}
|
||||
}
|
||||
|
||||
// 默认导出所有服务
|
||||
export default {
|
||||
userService,
|
||||
travelService,
|
||||
animalService,
|
||||
flowerService,
|
||||
orderService,
|
||||
paymentService,
|
||||
systemService,
|
||||
homeService,
|
||||
apiUtils
|
||||
}
|
||||
242
mini-program/api/types.js
Normal file
242
mini-program/api/types.js
Normal file
@@ -0,0 +1,242 @@
|
||||
// API 类型定义
|
||||
/**
|
||||
* 基础响应类型
|
||||
* @template T
|
||||
* @typedef {Object} BaseResponse
|
||||
* @property {number} code - 响应码 (0表示成功)
|
||||
* @property {string} message - 响应消息
|
||||
* @property {T} [data] - 响应数据
|
||||
* @property {number} [timestamp] - 时间戳
|
||||
*/
|
||||
|
||||
/**
|
||||
* 分页参数
|
||||
* @typedef {Object} PaginationParams
|
||||
* @property {number} [page] - 页码
|
||||
* @property {number} [pageSize] - 每页数量
|
||||
* @property {string} [keyword] - 搜索关键词
|
||||
*/
|
||||
|
||||
/**
|
||||
* 分页响应
|
||||
* @template T
|
||||
* @typedef {Object} PaginationResponse
|
||||
* @property {T[]} list - 数据列表
|
||||
* @property {number} total - 总数量
|
||||
* @property {number} page - 当前页码
|
||||
* @property {number} pageSize - 每页数量
|
||||
* @property {number} totalPages - 总页数
|
||||
*/
|
||||
|
||||
/**
|
||||
* 用户信息
|
||||
* @typedef {Object} UserInfo
|
||||
* @property {number} id - 用户ID
|
||||
* @property {string} username - 用户名
|
||||
* @property {string} nickname - 昵称
|
||||
* @property {string} avatar - 头像URL
|
||||
* @property {string} [phone] - 手机号
|
||||
* @property {string} [email] - 邮箱
|
||||
* @property {number} points - 积分
|
||||
* @property {number} level - 会员等级
|
||||
* @property {string} createTime - 创建时间
|
||||
*/
|
||||
|
||||
/**
|
||||
* 登录请求参数
|
||||
* @typedef {Object} LoginParams
|
||||
* @property {string} username - 用户名
|
||||
* @property {string} password - 密码
|
||||
*/
|
||||
|
||||
/**
|
||||
* 登录响应
|
||||
* @typedef {Object} LoginResponse
|
||||
* @property {string} token - 访问令牌
|
||||
* @property {string} refreshToken - 刷新令牌
|
||||
* @property {UserInfo} userInfo - 用户信息
|
||||
*/
|
||||
|
||||
/**
|
||||
* 旅行计划
|
||||
* @typedef {Object} TravelPlan
|
||||
* @property {number} id - 计划ID
|
||||
* @property {string} title - 标题
|
||||
* @property {string} destination - 目的地
|
||||
* @property {string} coverImage - 封面图
|
||||
* @property {string} startDate - 开始日期
|
||||
* @property {string} endDate - 结束日期
|
||||
* @property {number} budget - 预算
|
||||
* @property {number} currentMembers - 当前成员数
|
||||
* @property {number} maxMembers - 最大成员数
|
||||
* @property {string} description - 描述
|
||||
* @property {string} status - 状态
|
||||
* @property {UserInfo} creator - 创建者
|
||||
* @property {string} createTime - 创建时间
|
||||
*/
|
||||
|
||||
/**
|
||||
* 动物信息
|
||||
* @typedef {Object} AnimalInfo
|
||||
* @property {number} id - 动物ID
|
||||
* @property {string} name - 名称
|
||||
* @property {string} species - 种类
|
||||
* @property {number} price - 价格
|
||||
* @property {string} image - 图片
|
||||
* @property {string} description - 描述
|
||||
* @property {string} location - 位置
|
||||
* @property {boolean} isHot - 是否热门
|
||||
* @property {string} status - 状态
|
||||
* @property {string} createTime - 创建时间
|
||||
*/
|
||||
|
||||
/**
|
||||
* 花束信息
|
||||
* @typedef {Object} FlowerInfo
|
||||
* @property {number} id - 花束ID
|
||||
* @property {string} name - 名称
|
||||
* @property {string} description - 描述
|
||||
* @property {number} price - 价格
|
||||
* @property {string} image - 图片
|
||||
* @property {string} category - 分类
|
||||
* @property {number} stock - 库存
|
||||
* @property {string} createTime - 创建时间
|
||||
*/
|
||||
|
||||
/**
|
||||
* 订单信息
|
||||
* @typedef {Object} OrderInfo
|
||||
* @property {string} id - 订单ID
|
||||
* @property {string} orderNo - 订单编号
|
||||
* @property {string} type - 订单类型 (travel/animal/flower)
|
||||
* @property {string} title - 订单标题
|
||||
* @property {string} image - 图片
|
||||
* @property {number} price - 单价
|
||||
* @property {number} count - 数量
|
||||
* @property {number} totalAmount - 总金额
|
||||
* @property {string} status - 订单状态
|
||||
* @property {string} createTime - 创建时间
|
||||
* @property {string} [payTime] - 支付时间
|
||||
* @property {string} [completeTime] - 完成时间
|
||||
*/
|
||||
|
||||
/**
|
||||
* 支付信息
|
||||
* @typedef {Object} PaymentInfo
|
||||
* @property {string} paymentId - 支付ID
|
||||
* @property {number} amount - 支付金额
|
||||
* @property {string} status - 支付状态
|
||||
* @property {string} createTime - 创建时间
|
||||
* @property {string} [payTime] - 支付时间
|
||||
*/
|
||||
|
||||
/**
|
||||
* 系统公告
|
||||
* @typedef {Object} SystemNotice
|
||||
* @property {number} id - 公告ID
|
||||
* @property {string} title - 标题
|
||||
* @property {string} content - 内容
|
||||
* @property {string} type - 类型
|
||||
* @property {boolean} isActive - 是否激活
|
||||
* @property {string} createTime - 创建时间
|
||||
*/
|
||||
|
||||
/**
|
||||
* 错误码定义
|
||||
* @enum {number}
|
||||
*/
|
||||
export const ErrorCode = {
|
||||
SUCCESS: 0,
|
||||
UNAUTHORIZED: 401,
|
||||
FORBIDDEN: 403,
|
||||
NOT_FOUND: 404,
|
||||
INTERNAL_ERROR: 500,
|
||||
NETWORK_ERROR: 1001,
|
||||
PARAM_ERROR: 1002,
|
||||
BUSINESS_ERROR: 1003
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单状态
|
||||
* @enum {string}
|
||||
*/
|
||||
export const OrderStatus = {
|
||||
UNPAID: 'unpaid', // 待付款
|
||||
PAID: 'paid', // 已付款
|
||||
DELIVERED: 'delivered', // 已发货
|
||||
COMPLETED: 'completed', // 已完成
|
||||
CANCELLED: 'cancelled' // 已取消
|
||||
}
|
||||
|
||||
/**
|
||||
* 支付状态
|
||||
* @enum {string}
|
||||
*/
|
||||
export const PaymentStatus = {
|
||||
PENDING: 'pending', // 待支付
|
||||
SUCCESS: 'success', // 支付成功
|
||||
FAILED: 'failed', // 支付失败
|
||||
REFUNDED: 'refunded' // 已退款
|
||||
}
|
||||
|
||||
/**
|
||||
* 旅行计划状态
|
||||
* @enum {string}
|
||||
*/
|
||||
export const TravelStatus = {
|
||||
RECRUITING: 'recruiting', // 招募中
|
||||
FULL: 'full', // 已满员
|
||||
ONGOING: 'ongoing', // 进行中
|
||||
COMPLETED: 'completed', // 已完成
|
||||
CANCELLED: 'cancelled' // 已取消
|
||||
}
|
||||
|
||||
// 导出所有类型
|
||||
export default {
|
||||
BaseResponse,
|
||||
PaginationParams,
|
||||
PaginationResponse,
|
||||
UserInfo,
|
||||
LoginParams,
|
||||
LoginResponse,
|
||||
TravelPlan,
|
||||
AnimalInfo,
|
||||
FlowerInfo,
|
||||
OrderInfo,
|
||||
PaymentInfo,
|
||||
SystemNotice,
|
||||
ErrorCode,
|
||||
OrderStatus,
|
||||
PaymentStatus,
|
||||
TravelStatus
|
||||
}
|
||||
|
||||
// 类型检查工具
|
||||
export const TypeUtils = {
|
||||
/**
|
||||
* 检查是否为有效用户信息
|
||||
* @param {any} obj
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isUserInfo(obj) {
|
||||
return obj && typeof obj.id === 'number' && typeof obj.username === 'string'
|
||||
},
|
||||
|
||||
/**
|
||||
* 检查是否为有效旅行计划
|
||||
* @param {any} obj
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isTravelPlan(obj) {
|
||||
return obj && typeof obj.id === 'number' && typeof obj.destination === 'string'
|
||||
},
|
||||
|
||||
/**
|
||||
* 检查是否为有效订单信息
|
||||
* @param {any} obj
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isOrderInfo(obj) {
|
||||
return obj && typeof obj.id === 'string' && typeof obj.orderNo === 'string'
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user