flat: 暂存

This commit is contained in:
Apcallover
2024-04-18 16:42:36 +08:00
parent a044630563
commit bb7e57c361
2 changed files with 237 additions and 205 deletions

View File

@@ -24,5 +24,9 @@ module.exports = {
url: "" url: ""
} }
] ]
},
// 接口替换字符串
replaceStr: {
'{oss_file_url}': 'https://dy12333.org.cn/api'
} }
} }

View File

@@ -1,19 +1,22 @@
import { import {
OpenLoading, OpenLoading,
CloseLoading CloseLoading
} from "./Loading"; } from "./Loading";
import { import {
BASE_URL, BASE_URL,
AIRPORTS AIRPORTS
} from "./Constants"; } from "./Constants";
import website from "../config/website.js" import website from "../config/website.js"
import { import {
Base64 Base64
} from 'js-base64' } from 'js-base64'
import store from '@/store/'; import store from '@/store/';
import { import {
baseUrl baseUrl
} from '@/config/env.js' } from '@/config/env.js'
import {
replaceStr
} from "../config";
let showModal = true let showModal = true
/** /**
@@ -25,14 +28,14 @@ let showModal = true
* @returns {Promise<any>} * @returns {Promise<any>}
*/ */
export function DoGet(url, data = {}, config = {}) { export function DoGet(url, data = {}, config = {}) {
return DoAjax({ return DoAjax({
url: url, url: url,
data, data,
method: "GET", method: "GET",
dataType: "json" dataType: "json"
}, },
config config
); );
} }
/** /**
@@ -45,93 +48,118 @@ export function DoGet(url, data = {}, config = {}) {
*/ */
export function DoPost(url, data = {}, config = {}) { export function DoPost(url, data = {}, config = {}) {
return DoAjax({ return DoAjax({
url: url, url: url,
data, data,
method: "POST", method: "POST",
dataType: "json" dataType: "json"
}, },
config config
); );
} }
export function request(options) { export function request(options) {
const params = options.params const params = options.params
if (params) { if (params) {
let query = '' let query = ''
for (const key in params) { for (const key in params) {
if (params[key] !== undefined && params[key] !== null) { if (params[key] !== undefined && params[key] !== null) {
query += `&${key}=${params[key]}` query += `&${key}=${params[key]}`
} }
} }
query = '?' + query.substring(1) query = '?' + query.substring(1)
options.url += query options.url += query
} }
return DoAjax(options) return DoAjax(options)
} }
async function DoAjax(options, config = {}) { async function DoAjax(options, config = {}) {
const func = Promisify(uni.request); const func = Promisify(uni.request);
const header = options.headers || {}; const header = options.headers || {};
header["Authorization"] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`; header["Authorization"] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
const token = store.state.user.token; const token = store.state.user.token;
if (token) { if (token) {
header[website.tokenName] = "bearer " + token header[website.tokenName] = "bearer " + token
} }
if (baseUrl) { if (baseUrl) {
options.url = baseUrl + options.url options.url = baseUrl + options.url
} }
options = Object.assign({}, options, { options = Object.assign({}, options, {
header header
}); });
let res = null let res = null
try { try {
res = (await func(options)); res = (await func(options));
} catch (err) { } catch (err) {
console.log({ console.log({
err err
}) })
res = err; res = err;
res.data = {} res.data = {}
} finally {} } finally {}
// 获取状态码 // 获取状态码
const status = res.data.code || res.statusCode; const status = res.data.code || res.statusCode;
const statusWhiteList = website.statusWhiteList || []; const statusWhiteList = website.statusWhiteList || [];
let message = res.data.msg || res.data.error_description || '未知错误'; let message = res.data.msg || res.data.error_description || '未知错误';
//如果在白名单里则自行catch逻辑处理 //如果在白名单里则自行catch逻辑处理
if (statusWhiteList.includes(status)) throw res; if (statusWhiteList.includes(status)) throw res;
//如果是401则跳转到登录页面 //如果是401则跳转到登录页面
if (status === 401) { if (status === 401) {
store.dispatch('FedLogOut').then(() => { store.dispatch('FedLogOut').then(() => {
GoLogin() GoLogin()
}); });
throw new Error(message); throw new Error(message);
} }
// 如果请求为非200否者默认统一处理 // 如果请求为非200否者默认统一处理
if (status !== 200) { if (status !== 200) {
if (message === 'Bad credentials') { if (message === 'Bad credentials') {
message = '账号或密码错误' message = '账号或密码错误'
} }
uni.showToast({ uni.showToast({
title: message, title: message,
icon: 'none' icon: 'none'
}); });
throw new Error(message); throw new Error(message);
} }
return res; return transformRepalceString(res);
} }
// 递归替换 url
function transformRepalceString(props) {
if (typeof props !== 'object' || props === null) {
for (const key in replaceStr) {
if (typeof props === 'string') {
props = props.replace(key, replaceStr[key]);
}
}
return props;
}
let result;
if (props instanceof Array) {
result = [];
} else {
result = {};
}
for (let key in props) {
if (props.hasOwnProperty(key)) {
result[key] = transformRepalceString(props[key]);
}
}
return result;
}
/** /**
* 时间格式化 * 时间格式化
* @param {*} str * @param {*} str
* @param {string} fmt * @param {string} fmt
*/ */
export function DateFormat(str, fmt = "YYYY-MM-DD HH:mm:ss") { export function DateFormat(str, fmt = "YYYY-MM-DD HH:mm:ss") {
return str ? moment(str).format(fmt) : "--"; return str ? moment(str).format(fmt) : "--";
} }
/** /**
@@ -141,46 +169,46 @@ export function DateFormat(str, fmt = "YYYY-MM-DD HH:mm:ss") {
* @returns * @returns
*/ */
export function HtmlImgAddHost(html) { export function HtmlImgAddHost(html) {
return html.replace( return html.replace(
/ src="\//g, / src="\//g,
` style="width:100% !important" src="${BASE_URL}/` ` style="width:100% !important" src="${BASE_URL}/`
); );
} }
export function Promisify(func) { export function Promisify(func) {
return function(data) { return function(data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
func({ func({
...data, ...data,
success: resolve, success: resolve,
fail: reject fail: reject
}); });
}); });
}; };
} }
export function GoLogin() { export function GoLogin() {
if (showModal) { if (showModal) {
showModal = false showModal = false
location.href = "https://dy12333.org.cn/h5/" location.href = "https://dy12333.org.cn/h5/"
// uni.showModal({ // uni.showModal({
// title: "提示", // title: "提示",
// content: "您还未登录,点击确认去登录", // content: "您还未登录,点击确认去登录",
// success({ // success({
// confirm // confirm
// }) { // }) {
// if (confirm) { // if (confirm) {
// uni.redirectTo({ // uni.redirectTo({
// url: "/pages/login/login" // url: "/pages/login/login"
// }); // });
// } // }
// showModal = true // showModal = true
// }, // },
// fail() { // fail() {
// showModal = true // showModal = true
// } // }
// }) // })
} }
} }
/** /**
@@ -189,17 +217,17 @@ export function GoLogin() {
* @param {string[]} list * @param {string[]} list
*/ */
export function GetServiceIata(...list) { export function GetServiceIata(...list) {
const dic = new Set(AIRPORTS); const dic = new Set(AIRPORTS);
for (let i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
if (dic.has(list[i])) return list[i]; if (dic.has(list[i])) return list[i];
} }
return AIRPORTS[0]; return AIRPORTS[0];
} }
export async function confirm(options) { export async function confirm(options) {
const func = Promisify(wx.showModal); const func = Promisify(wx.showModal);
const res = await func(options); const res = await func(options);
if (res.confirm !== true) throw new Error(res.cancel); if (res.confirm !== true) throw new Error(res.cancel);
} }