mtl-js-sdk
Version:
ynf-fw-mtl-api
365 lines (348 loc) • 13.6 kB
JavaScript
/*
* @Author: wangyingliang@yonyou.com
* @Date: 2024-04-01 16:06:36
* @LastEditors: wangyingliang wangyingliang@yonyou.com
* @LastEditTime: 2025-04-07 17:59:36
* @FilePath: /mtl-api-project/src/platforms/yyzone/network/index.js
* @Description: 网络模块
* Copyright (c) 2024 by Yonyou, All Rights Reserved.
*/
import { invokeSuccess, invokeFail } from '../callback'
import { requestPermission } from '../permission'
import { canExecUpesnBridge } from '../bridge/index'
import { getUnifiedSessionHeader } from '../util'
import sha1 from 'sha1'
export function request(param = {}) {
console.log('[mtl]request');
if (param.url && !param.url.startsWith("http")) {
axiosRequest(param);
return;
}
getUnifiedSessionHeader({
unifiedSession: param.unifiedSession,
success: function (requestHeader) {
let p = { dataType: 'text', returnAll: true };
p.url = param.url;
p.method = param.method || 'GET';
p.timeout = param.timeout || 30;
p.headers = param.headers || param.header || {};
for (const key in requestHeader) {
if (Object.hasOwnProperty.call(requestHeader, key)) {
if (!p.headers[key]) {
p.headers[key] = requestHeader[key];
}
}
}
if (param.paramsType === 0) {
p.data = { values: param.params };
} else {
p.data = { body: param.params };
if (!p.headers["Content-Type"] && !p.headers["content-type"]) {
p.headers["Content-Type"] = "application/json;charset=utf-8;";
}
}
api.ajax(p, function (ret, err) {
if (ret) {
let res = { status: ret.statusCode, headers: ret.headers, data: ret.body };
invokeSuccess(param, res);
} else {
let code = err.statusCode || err.code;
if (code === 0) {
code = 1001;
} else if (code === 1) {
code = -2;
} else if (code === 2) {
code = 401;
} else if (code === 3) {
code = 1002;
} else if (code === 404) {
code = -1;
}
invokeFail(param, { code: code, message: err.msg });
}
});
}
});
}
export function uploadFile(param = {}) {
if (canExecUpesnBridge() && api.systemType === 'ios' && param.filePath && !api.require('fs').existSync({ path: param.filePath }).exist) {
let trans = api.require('trans');
if (trans && trans.batchTransPath) {
trans.batchTransPath({
paths: [param.filePath]
}, function (ret, err) {
if (ret && ret.paths && ret.paths.length > 0) {
_uploadFile({ ...param, filePath: ret.paths[0] });
} else {
_uploadFile(param);
}
});
} else {
_uploadFile(param);
}
} else {
_uploadFile(param);
}
}
function _uploadFile(param) {
console.log('[mtl]upload file: ' + param.filePath);
getUnifiedSessionHeader({
unifiedSession: param.unifiedSession,
success: function (requestHeader) {
let p = { dataType: 'text', returnAll: true };
let name = param.name || 'file';
let files = {};
files[name] = param.filePath;
p.url = param.url;
p.method = param.method || 'POST';
p.timeout = param.timeout || 30;
p.headers = param.header || param.headers || {};
for (const key in requestHeader) {
if (Object.hasOwnProperty.call(requestHeader, key)) {
if (!p.headers[key]) {
p.headers[key] = requestHeader[key];
}
}
}
p.data = {
values: param.formData,
files: files
}
api.ajax(p, function (ret, err) {
if (ret) {
let res = { statusCode: ret.statusCode, headers: ret.headers, data: ret.body };
invokeSuccess(param, res);
} else {
invokeFail(param, err);
}
});
}
});
}
export function downloadFile(param = {}) {
console.log('[mtl]downloadFile');
if (!param.url) {
invokeFail(param, { msg: 'url is null' });
return;
}
if (canExecUpesnBridge()) {
window.mtl?.execUpesnBridge({ method: 'downloadFile', ...param })
return;
}
requestPermission({
list: ['storage-r'],
success: function () {
getUnifiedSessionHeader({
unifiedSession: param.unifiedSession,
success: function (requestHeader) {
let {
url,
timeout = 30,
fileType,
fileName,
autoPreview,
header,
headers,
formBody,
jsonBody
} = param;
if (fileType && !fileName) {
fileName = `${new Date().getTime()}.${fileType}`
}
let p = {allowResume: true};
p.url = url;
p.timeout = timeout;
if (fileName) {
p.savePath = `cache://${sha1(url)}/${fileName}`
}
p.headers = header || headers || {};
for (const key in requestHeader) {
if (Object.hasOwnProperty.call(requestHeader, key)) {
if (!p.headers[key]) {
p.headers[key] = requestHeader[key];
}
}
}
if (formBody && Object.keys(formBody).length > 0) {
p.method = 'POST';
p.data = { values: formBody };
} else if (typeof jsonBody == 'string' && jsonBody.length > 2) {
p.method = 'POST';
p.data = { body: jsonBody };
p.headers['Content-Type'] = 'application/json;charset=utf-8;';
}
api.download(p, function (ret, err) {
if (ret) {
if (ret.state === 1) {
let res = { filePath: ret.savePath };
invokeSuccess(param, res);
if (autoPreview === 1) {
mtl.openLocalFile({
filePath: ret.savePath,
fileType: fileType
});
}
} else if (ret.state === 2) {
invokeFail(param, {});
}
} else {
invokeFail(param, err);
}
});
}
});
},
fail: param.fail
});
}
export function setCookie(param = {}) {
if (param.url && param.cookie) {
api.setCookie(param);
invokeSuccess(param, {});
} else {
invokeFail(param, { message: 'param error' });
}
}
function axiosRequest(object) {
var axios = require("axios");
axios = axios?.default || axios
if (axios) {
axios(object).then(res => {
let { status: code, statusText: message, data } = res;
if (code === 200) {
object.success && object.success(data);
} else {
object.fail && object.fail({ code, message, data });
}
object.complete && object.complete({ code, message, data });
}).catch(err => {
const result = { code: 1, message: err.message };
object.fail && object.fail(result);
object.complete && object.complete(result);
});
} else {
console.log('-------- axios is null')
}
}
/**
* 上传接口, 6.2.14版本增加, 后续统一替换.
* @param {string} serviceCode 服务编码, 非必传.
* @param {string} url 自定义上传文件地址, 非必传.
* @param {string} name filePath 对应的 key, 非必传.
* @param {string} filePath 文件路径, 多文件暂不支持.
* @param {string} method 请求类型, 非必传.
* @param {string} timeout 超时时间 毫秒, 非必传.
* @param {object} formData 其他额外参数.
* @param {string} formData.businessType 领域类型, 需要单独到文件服务注册, 必传.
* @param {string} formData.businessId 领域ID, 必传.
* @param {string} formData.usePrivateBucket 是否使用私有桶, 必传.
* @param {object} header 请求头参数吗, 以传入的为主, 非必传.
*/
export function uploadToFileService(param) {
if (!param?.filePath) {
invokeFail(param, {
code: '-1004',
msg: 'File service: filePath is null!'
});
return
}
if (canExecUpesnBridge() && api.systemType === 'ios' && param.filePath && !api.require('fs').existSync({ path: param.filePath }).exist) {
let trans = api.require('trans');
if (trans && trans.batchTransPath) {
trans.batchTransPath({
paths: [param.filePath]
}, function (ret, err) {
if (ret && ret.paths && ret.paths.length > 0) {
_uploadFileService({ ...param, filePath: ret.paths[0] });
} else {
_uploadFileService(param);
}
});
} else {
_uploadFileService(param);
}
} else {
_uploadFileService(param);
}
}
function _uploadFileService(param) {
console.log('[mtl]upload param: ' + param);
getUnifiedSessionHeader({
unifiedSession: param?.unifiedSession,
success: function (requestHeader) {
if (!param?.url) {
// 去移动端获取对应租户的数据中心域名
mtl.getMultiDataCenterConfig({
success: function (res) {
let tenantId = res.currentTenantID
let serviceCode = param?.serviceCode || "iuap-apcom-file"
console.log(res)
// 使用多数据中心逻辑获取域名
// 如果 serviceCode 存在需要查询是否在多数据中心环境
let multidataCodeList = res.multidata?.multidataCode // 多数据中心域名
let domainCodeList = res.domain?.domainCode // 社会化服务域名
let domainUrl = ''
if (multidataCodeList[serviceCode]) {
domainUrl = res.multidata.multidataUrl[tenantId]
} else if (domainCodeList[serviceCode]) {
domainUrl = res.domain.domainUrl
} else {
domainUrl = window.location.origin // 社会化域名
}
domainUrl = domainUrl.endsWith('/') ? domainUrl : domainUrl + "/"
let url = domainUrl + 'iuap-apcom-file/rest/mtl/file/upload'
param.url = url
sendFileRquest(param, requestHeader)
},
fail: function (err) {
console.log(err)
// 采用 window.location.origin
let url = window.location.origin + '/iuap-apcom-file/rest/mtl/file/upload'
param.url = url
sendFileRquest(param, requestHeader)
}
});
} else {
sendFileRquest(param, requestHeader)
}
}
});
}
function sendFileRquest(param, requestHeader = {}) {
let url = param?.url
let p = {
dataType: 'text',
returnAll: true
};
let name = param?.name || 'file';
let files = {};
files[name] = param?.filePath; // TODO: string || array
p.url = url;
p.method = param?.method || 'POST';
p.timeout = param?.timeout || 30;
p.headers = param?.header || param?.headers || {};
for (const key in requestHeader) {
if (Object.hasOwnProperty.call(requestHeader, key)) {
if (!p.headers[key]) {
p.headers[key] = requestHeader[key];
}
}
}
p.data = {
values: param?.formData,
files: files
}
// 注意 ios 虚拟路径.
window.api.ajax(p, function (ret, err) {
if (ret) {
let res = {
statusCode: ret.statusCode,
headers: ret.headers,
data: JSON.parse(ret.body)
};
invokeSuccess(param, res);
} else {
invokeFail(param, err);
}
});
}