mothercup/SmartAssiter/api/httpInstance.ts
2026-09-04 08:56:15 +08:00

90 lines
2.3 KiB
TypeScript
Raw Permalink 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.

import { getToken } from "../common/auth"
import { clearAllData } from "../common/auth"
// 通用 JSON 对象类型(替代 uts 的 UTSJSONObject)
export type JSONObject = Record<string, any>
// 可选后台服务器列表
export type ServerItem = {
name: string
url: string
}
export const SERVER_LIST: ServerItem[] = [
{ name: "正式 ssl (evmtapp.clenergy.com)", url: "https://evmtapp.clenergy.com:20096" } as ServerItem,
{ name: "测试 (47.107.245.120)", url: "http://47.107.245.120:30081" } as ServerItem,
{ name: "DEBUG (192.168.13.158)", url: "http://192.168.13.158:30081" } as ServerItem
]
let recordBaseUrl: string | null = null
// 读取当前后台服务器地址(内存 + 本地),未选择过则默认第一个
export function getBaseUrl(): string {
if (recordBaseUrl != null && recordBaseUrl.length > 0) {
return recordBaseUrl
}
const t = uni.getStorageSync('serverBaseUrl') as string
if (t != null && t.length > 0) {
recordBaseUrl = t
return t
}
return SERVER_LIST[0].url
}
// 保存后台服务器地址(内存 + 本地),下次启动直接加载
export function setBaseUrl(url: string) {
recordBaseUrl = url
uni.setStorageSync('serverBaseUrl', url)
}
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE"
// 请求参数类型
export type HttpRequest = {
url: string
method?: HttpMethod
data?: any
header?: JSONObject
}
// 封装请求
export function $http(params: HttpRequest): Promise<JSONObject> {
return new Promise((resolve, reject) => {
// 1. 准备 header
let baseHeader: JSONObject = params.header ?? {} as JSONObject
baseHeader["Content-Type"] = "application/json"
// 2. 读 token,有就加 Authorization
const token = getToken()
if (token != null && token.length > 0) {
baseHeader["Authorization"] = token
}
// 3. 发请求
uni.request({
url: getBaseUrl() + params.url,
method: params.method ?? "GET",
data: params.data ?? {} as JSONObject,
header: baseHeader,
success: (res) => {
if(res.statusCode == 401) {
clearAllData()
uni.reLaunch({
url: '/pages/login/login'
})
}
const result: JSONObject = {
statusCode: res.statusCode,
data: res.data
} as JSONObject
resolve(result)
},
fail: (err) => {
reject(err)
}
})
})
}