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