feat: 搭建微信小程序展示端
- 初始化小程序工程配置与类型声明 - 增加首页、律所、律师列表、详情与历史页面 - 补充公共组件、运行时配置与示例素材
This commit is contained in:
75
frontend_miniprogram/miniprogram/utils/http.ts
Normal file
75
frontend_miniprogram/miniprogram/utils/http.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { API_BASE_URL_OVERRIDE_KEY, tenantRuntimeConfig } from '../config/runtime';
|
||||
import { getMiniappAppId, getMiniappEnvVersion } from './miniapp';
|
||||
|
||||
interface ApiResponse<T> {
|
||||
code: string;
|
||||
message: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
url: string;
|
||||
method?: 'GET' | 'POST';
|
||||
data?: WechatMiniprogram.IAnyObject;
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(baseUrl: string): string {
|
||||
return baseUrl.trim().replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
function getApiBaseUrl(): string {
|
||||
const override = wx.getStorageSync(API_BASE_URL_OVERRIDE_KEY);
|
||||
if (typeof override === 'string' && override.trim()) {
|
||||
return normalizeBaseUrl(override);
|
||||
}
|
||||
|
||||
const envVersion = getMiniappEnvVersion();
|
||||
const baseUrl = tenantRuntimeConfig.apiBaseUrlByEnv[envVersion];
|
||||
if (!baseUrl || !baseUrl.trim()) {
|
||||
throw new Error(`未配置 ${envVersion} 环境的接口域名`);
|
||||
}
|
||||
|
||||
const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
|
||||
if (envVersion !== 'develop' && !normalizedBaseUrl.startsWith('https://')) {
|
||||
throw new Error(`${envVersion} 环境接口域名必须使用 HTTPS`);
|
||||
}
|
||||
|
||||
return normalizedBaseUrl;
|
||||
}
|
||||
|
||||
export function request<T>(options: RequestOptions): Promise<T> {
|
||||
const appId = getMiniappAppId();
|
||||
if (!appId) {
|
||||
return Promise.reject(new Error('未获取到小程序 AppID'));
|
||||
}
|
||||
|
||||
let apiBaseUrl = '';
|
||||
try {
|
||||
apiBaseUrl = getApiBaseUrl();
|
||||
} catch (error) {
|
||||
return Promise.reject(error instanceof Error ? error : new Error('接口域名配置无效'));
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.request({
|
||||
url: `${apiBaseUrl}${options.url}`,
|
||||
method: options.method || 'GET',
|
||||
data: options.data,
|
||||
header: {
|
||||
'X-Miniapp-Appid': appId,
|
||||
},
|
||||
success: (response) => {
|
||||
const payload = response.data as ApiResponse<T> | undefined;
|
||||
if (response.statusCode >= 200 && response.statusCode < 300 && payload && payload.code === '0') {
|
||||
resolve(payload.data);
|
||||
return;
|
||||
}
|
||||
const message = payload && payload.message ? payload.message : '请求失败';
|
||||
reject(new Error(message));
|
||||
},
|
||||
fail: () => {
|
||||
reject(new Error('网络异常,请稍后重试'));
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user