UNPKG

@farris/bef-vue

Version:
1,789 lines (1,788 loc) 131 kB
var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; import { HttpUtil, Devkit, HttpMethods, EXCEPTION_HANDLER_TOKEN, Repository, HttpClient, createEntitiesBySchema, EntityPathNodeType, FieldType, ViewModel } from "@farris/devkit-vue"; var ContentType = /* @__PURE__ */ ((ContentType2) => { ContentType2[ContentType2["NONE"] = 0] = "NONE"; ContentType2[ContentType2["JSON"] = 1] = "JSON"; ContentType2[ContentType2["FORM"] = 2] = "FORM"; ContentType2[ContentType2["FORM_DATA"] = 3] = "FORM_DATA"; ContentType2[ContentType2["TEXT"] = 4] = "TEXT"; ContentType2[ContentType2["BLOB"] = 5] = "BLOB"; ContentType2[ContentType2["ARRAY_BUFFER"] = 6] = "ARRAY_BUFFER"; return ContentType2; })(ContentType || {}); class BefHttpUtil { /** * 追加SessionId头 */ static appendSessionId(headers, sessionId) { headers = HttpUtil.appendHeader(headers, "SessionId", sessionId); return headers; } /** * 追加CommonVariable头 * @summary * 框架会话token,等价于原来的SessionId */ static appendCafRuntimeCommonVariable(headers, commonVariable) { headers = HttpUtil.appendHeader(headers, "X-CAF-Runtime-CommonVariable", commonVariable); return headers; } /** * 追加X-CAF-Runtime-Context头 * @summary * X-CAF-Runtime-Context等价于BeSessionId */ static appendCafRuntimeContext(headers, context) { headers = HttpUtil.appendHeader(headers, "X-CAF-Runtime-Context", context); return headers; } /** * 追加Content-Type头 * @summary * 提交内容的MIME类型,默认为application/json */ static appendContextType(headers, contentType) { contentType = contentType || "application/json"; headers = HttpUtil.appendHeader(headers, "Content-Type", contentType); return headers; } /** * 追加Func-Inst-Id * @param headers * @param funcInstId * @returns */ static appendFuncInstId(headers, funcInstId) { return headers.append("Func-Inst-Id", funcInstId); } } class BefEnvUtil { /** * 是否在框架内运行 */ static isInFramework() { const hashString = window.location.hash; if (!hashString) { return false; } return hashString.indexOf("formToken=") !== -1; } } class FrameworkSessionService { /** * 构造函数 */ constructor() { __publicField(this, "rtfService"); __publicField(this, "frameworkService", null); this.rtfService = this.getRuntimeFrameworkService(); } /** * 获取当前会话id */ getCurrentSessionId() { return this.formToken || ""; } get tabId() { return this.params && this.params["tabId"] || null; } /** * 获取formToken */ get formToken() { return this.params && this.params["cvft"] || null; } get params() { const hash = window.location.hash; const params = this.parseQueryString(hash); return params; } getRuntimeFrameworkService() { const frameworkService = this.gspFrameworkService; return frameworkService && frameworkService.rtf || {}; } get gspFrameworkService() { if (this.frameworkService) { return this.frameworkService; } let env = window; while (!env["gspframeworkService"] && env !== window.top && this.isSameOrigin(env)) { env = env.parent; } this.frameworkService = env["gspframeworkService"]; return this.frameworkService; } isSameOrigin(environment) { const host = window.location.host; try { if (environment && environment.location && typeof environment.location.host !== "undefined") { return environment.location.host === host; } } catch (e) { return false; } return false; } parseQueryString(queryString) { if (!queryString) { return {}; } const hashes = queryString.slice(queryString.indexOf("?") + 1).split("&"); return hashes.reduce((params, hash) => { const split = hash.indexOf("="); const key = hash.slice(0, split); const val = hash.slice(split + 1); return Object.assign(params, { [key]: decodeURIComponent(val) }); }, {}); } } class SessionHandlingStrategy { /** * 构造函数 */ constructor(storageStrategy, frameworkSessionService, httpClient, baseUrl, injector) { /** * 存储策略 */ __publicField(this, "storageStrategy"); /** * 框架Session服务 */ __publicField(this, "frameworkSessionService"); /** * Http客户端 */ __publicField(this, "httpClient"); /** * 创建Session的的EAPI地址 */ __publicField(this, "baseUrl"); /** * 创建Session接口地址 */ __publicField(this, "createSessionUrl"); /** * 关闭Session接口地址 */ __publicField(this, "closeSessionUrl"); /** * 上次使用的会话id */ __publicField(this, "lastTimeUsedSessionId"); /** * injector */ __publicField(this, "injector"); this.storageStrategy = storageStrategy; this.frameworkSessionService = frameworkSessionService; this.httpClient = httpClient; this.baseUrl = baseUrl; this.createSessionUrl = `${baseUrl}/service/createsession`; this.closeSessionUrl = `${baseUrl}/service/closesession`; this.injector = injector; } /** * 获取框架SessionId * TODO: 暂不支持runtimeContext */ getFrameworkSessionId() { return this.frameworkSessionId; } /** * 从缓存中获取BeSession */ getSessionIdFromStorage(runtimeContext) { const sessionStorageKey = this.getSessionStorageKey(runtimeContext); const beSessionId = this.storageStrategy.getItem(sessionStorageKey); return beSessionId; } /** * 框架SessionId(用户的或者功能菜单的) */ get frameworkSessionId() { return this.frameworkSessionService.getCurrentSessionId(); } } class BefSeparatedSessionHandlingStrategy extends SessionHandlingStrategy { /** * 构造函数 */ constructor(storageStrategy, frameworkSessionService, httpClient, baseUrl, injector) { super(storageStrategy, frameworkSessionService, httpClient, baseUrl, injector); } /** * 获取BeSessionId */ getSessionId(runtimeContext) { const beSessionId = this.getSessionIdFromStorage(runtimeContext); if (beSessionId) { return Promise.resolve(beSessionId); } const sessionIdPromise = this.closeLastTimeUsedSession().then(() => { return this.createSession(runtimeContext); }); return sessionIdPromise; } /** * 创建BeSessionId */ createSession(runtimeContext) { const requestConfig = { responseType: "text", headers: { "Content-Type": "application/json" } }; requestConfig.headers = BefHttpUtil.appendCafRuntimeCommonVariable(requestConfig.headers, this.frameworkSessionId); return this.httpClient.post(this.createSessionUrl, null, requestConfig).then((beSessionId) => { this.setSessionId(beSessionId, runtimeContext); return beSessionId; }); } /** * 关闭上次使用的会话 */ closeLastTimeUsedSession() { if (!this.lastTimeUsedSessionId) { return Promise.resolve(true); } const requestConfig = { responseType: "text", headers: { "Content-Type": "application/json" } }; requestConfig.headers = BefHttpUtil.appendCafRuntimeContext(requestConfig.headers, this.lastTimeUsedSessionId); requestConfig.headers = BefHttpUtil.appendCafRuntimeCommonVariable(requestConfig.headers, this.frameworkSessionId); return this.httpClient.post(this.closeSessionUrl, null, requestConfig).then(() => { return true; }); } /** * 设置BeSessionId */ setSessionId(sessionId, runtimeContext) { const sessionKey = this.getSessionStorageKey(runtimeContext); this.storageStrategy.setItem(sessionKey, sessionId); } /** * 清空BeSessionId */ clearSessionId(runtimeContext) { if (BefEnvUtil.isInFramework() === true) { this.storageStrategy.removeItemsByScope(this.frameworkSessionId); } else { const sessionKey = this.getSessionStorageKey(runtimeContext); this.lastTimeUsedSessionId = this.getSessionIdFromStorage(runtimeContext); this.storageStrategy.removeItem(sessionKey); } } /** * 扩展BeSessionId相关头信息 */ handleRequestHeaders(headers, runtimeContext) { const frmSessionId = this.getFrameworkSessionId(); const beSessionId = this.getSessionIdFromStorage(runtimeContext); headers = BefHttpUtil.appendCafRuntimeCommonVariable(headers, frmSessionId); if (beSessionId) { headers = BefHttpUtil.appendCafRuntimeContext(headers, beSessionId); headers = BefHttpUtil.appendSessionId(headers, beSessionId); } return headers; } /** * 处理服务器端返回的headers */ handleReponseHeaders(headers) { } /** * 获取某个Repository对应的BeSession的唯一key */ getSessionStorageKey(runtimeContext) { let sessionId = this.frameworkSessionId; if (runtimeContext) { sessionId = this.getFrameworkSessionId(); } const tabId = runtimeContext && runtimeContext.tabId; if (tabId) { return `${sessionId}_${tabId}_${this.baseUrl}`; } return `${sessionId}_${this.baseUrl}`; } } class BefUnifiedSessionHandlingStrategy extends SessionHandlingStrategy { /** * 构造函数 */ constructor(storageStrategy, frameworSessionService, httpClient, baseUrl, injector) { super(storageStrategy, frameworSessionService, httpClient, baseUrl, injector); this.injector = injector; } /** * 获取会话复用的session id * @param runtimeContext runtime context */ getSessionId(runtimeContext) { const sessionKey = this.getSessionStorageKey(runtimeContext); const sessionId = this.storageStrategy.getItem(sessionKey); return Promise.resolve(sessionId); } /** * 设置session id * @param sessionId session id * @param runtimeContext runtime context */ setSessionId(sessionId, runtimeContext) { const sessionKey = this.getSessionStorageKey(runtimeContext); this.storageStrategy.setItem(sessionKey, sessionId); } /** * 清空session id * @param runtimeContext runtime context */ clearSessionId(runtimeContext) { const sessionKey = this.getSessionStorageKey(runtimeContext); this.storageStrategy.removeItem(sessionKey); } /** * 处理请求header * @param headers * @param runtimeContext runtime context */ handleRequestHeaders(headers, runtimeContext) { const frmSessionId = this.getFrameworkSessionId(); const beSessionId = this.getSessionIdFromStorage(runtimeContext); const devkit = this.injector.get(Devkit, void 0); if (devkit) { const funcInstId = ""; headers = BefHttpUtil.appendFuncInstId(headers, funcInstId); } headers = BefHttpUtil.appendCafRuntimeCommonVariable(headers, frmSessionId); if (beSessionId) { headers = BefHttpUtil.appendCafRuntimeContext(headers, beSessionId); } return headers; } /** * 处理返回header * @param headers */ handleReponseHeaders(headers) { } /** * 构造session存储的key * @param runtimeContext runtime context */ getSessionStorageKey(runtimeContext) { let sessionId = this.frameworkSessionId; if (runtimeContext) { sessionId = this.getFrameworkSessionId(); } const tabId = runtimeContext && runtimeContext.tabId; if (tabId) { return `${sessionId}_${tabId}_${this.baseUrl}`; } return `${sessionId}_${this.baseUrl}`; } } class SessionStorageStrategy { constructor() { /** * 缓存Token */ __publicField(this, "sessionStorageKey", "BE_SESSION_ID"); } /** * 获取值 */ getItem(beSessionKey) { const beSessions = this.getAllBeSessions(); return beSessions[beSessionKey]; } /** * 设置值 */ setItem(beSessionKey, beSessionId) { const beSessions = this.getAllBeSessions(); beSessions[beSessionKey] = beSessionId; this.setAllBeSessions(beSessions); } /** * 删除值 */ removeItem(beSessionKey) { const beSessions = this.getAllBeSessions(); if (beSessions[beSessionKey]) { delete beSessions[beSessionKey]; } this.setAllBeSessions(beSessions); } /** * 根据scope删除值 */ removeItemsByScope(beSessionScope) { const beSessions = this.getAllBeSessions(); Object.keys(beSessions).forEach((beSessionKey) => { if (beSessionKey.startsWith(beSessionScope) === true) { delete beSessions[beSessionKey]; } }); this.setAllBeSessions(beSessions); } /** * 清空所有会话 */ clear() { window.sessionStorage.removeItem(this.sessionStorageKey); } /** * 从SessionStorage中获取全部BeSessions */ getAllBeSessions() { const beSessionsJson = window.sessionStorage.getItem(this.sessionStorageKey); if (!beSessionsJson) { return {}; } return JSON.parse(beSessionsJson); } /** * 设置全部BeSessions到SessionStorage */ setAllBeSessions(beSessions) { const beSessionsString = JSON.stringify(beSessions); window.sessionStorage.setItem(this.sessionStorageKey, beSessionsString); } } class BefSessionHandlingStrategyFactory { /** * 创建BeSession处理策略 */ create(handlingStrategyName, frmSessionService, beBaseUrl, httpClient, injector) { const storageStrategy = this.createStorageStrategy(); if (handlingStrategyName === "UnifiedSession") { return new BefUnifiedSessionHandlingStrategy(storageStrategy, frmSessionService, httpClient, beBaseUrl, injector); } else { return new BefSeparatedSessionHandlingStrategy(storageStrategy, frmSessionService, httpClient, beBaseUrl, injector); } } /** * 创建BeSession缓存策略 */ createStorageStrategy() { return new SessionStorageStrategy(); } } class BefSessionService { /** * 构造函数 */ constructor(handlingStrategy) { /** * Session处理策略类 */ __publicField(this, "handlingStrategy"); this.handlingStrategy = handlingStrategy; } /** * 获取token */ get token() { return this.handlingStrategy.getFrameworkSessionId(); } /** * 获取BeSessionId */ getBeSessionId(runtimeContext) { return this.handlingStrategy.getSessionId(runtimeContext); } /** * 设置sessionId * @param sessionId sessionId */ setBeSessionId(sessionId, runtimeContext) { this.handlingStrategy.setSessionId(sessionId, runtimeContext); } /** * 清空BeSessionId */ clearBeSessionId(runtimeContext) { this.handlingStrategy.clearSessionId(runtimeContext); } /** * 扩展请求header */ extendRequestHeaders(headers, runtimeContext) { return this.handlingStrategy.handleRequestHeaders(headers, runtimeContext); } /** * 处理响应header */ handleResponseHeaders(headers) { return this.handlingStrategy.handleReponseHeaders(headers); } } class BefSessionManager { static getSessionId(moduleId, sessionService, beBaseUri, runtimeContext) { const key = `${moduleId}_${beBaseUri}`; const createSessionIsInvoked = this.history.includes(key); if (createSessionIsInvoked) { return Promise.resolve(null); } else { this.history.push(key); return sessionService.getBeSessionId(runtimeContext); } } } __publicField(BefSessionManager, "history", []); class BefProxy { /** * 构造函数 */ constructor(httpClient) { /** * 基路径 */ __publicField(this, "baseUrl"); /** * 代理扩展 */ __publicField(this, "proxyExtend"); this.httpClient = httpClient; } /** * 初始化 */ init(baseUrl) { this.baseUrl = baseUrl; } /** * 设置扩展策略 */ setProxyExtend(proxyExtend) { this.proxyExtend = proxyExtend; } /** * 列表数据查询(扩展) */ extendQuery(entityFilter) { return this.wrapAsync(() => { const url = `${this.baseUrl}/extension/query`; const params = {}; if (entityFilter) { const entityFilterString = JSON.stringify(entityFilter); params.entityFilter = entityFilterString; } const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { params, body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 查询数据 * @param entityFilter 过滤、排序、分页信息 * @returns * @description 和extendQuery类似,区别在于将查询参数放到body中 */ filter(entityFilter) { return this.wrapAsync(() => { let url = `${this.baseUrl}/extension/filter`; const body = {}; if (entityFilter) { body.entityFilter = entityFilter; } const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.POST, url, requestConfig); }); } /** * 单条数据检索(扩展) */ extendRetrieve(id) { return this.wrapAsync(() => { const url = `${this.baseUrl}/extension/retrieve/${encodeURIComponent(id)}`; const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 加锁编辑数据 * @param id * @returns */ edit(id) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/edit/${encodeURIComponent(id)}`; const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 新增数据 */ create(defaultValue) { return this.wrapAsync(() => { const body = {}; body.defaultValue = defaultValue; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.POST, this.baseUrl, requestConfig); }); } /** * 批量新增主表数据 * @param defaultValues 字段默认值,keyvalue格式 * @returns */ batchCreate(defaultValues) { return this.wrapAsync(() => { const url = `${this.baseUrl}/batch`; const body = {}; if (defaultValues && defaultValues.length > 0) { body.retrieveDefaultParam = { defaultValues }; } const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.POST, url, requestConfig); }); } /** * 新增从表或从从表数据 * @param fpath 实体路径 * @param defaultValues 默认值,keyvalue格式 * @returns */ createByPath(fpath, defaultValues) { return this.wrapAsync(() => { const pathUrl = this.convertPathToUrl(fpath); const url = `${this.baseUrl}${pathUrl}`; const body = {}; if (defaultValues && defaultValues.length > 0) { body.retrieveDefaultParam = { defaultValues }; } const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.POST, url, requestConfig); }); } /** * 批量新增从表或从从表数据 * @param path * @param defaultValues * @returns */ batchCreateByPath(path, defaultValues) { return this.wrapAsync(() => { const pathUrl = this.convertPathToUrl(path); const url = `${this.baseUrl}${pathUrl}/batch`; const body = {}; if (defaultValues && defaultValues.length > 0) { body.retrieveDefaultParam = { defaultValues }; } const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.POST, url, requestConfig); }); } update(changeDetails) { return this.wrapAsync(() => { const body = { changeDetails }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PATCH, this.baseUrl, requestConfig); }); } /** * 保存 */ save() { return this.wrapAsync(() => { const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, this.baseUrl, requestConfig); }); } /** * 删除 */ extendDelete(id) { return this.wrapAsync(() => { const url = `${this.baseUrl}/extension/delete/${id}`; const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 删除从表或从从表数据 * @param fpath 实体路径 * @param id 实体id * @returns */ extendDeletByPath(fpath, id) { return this.wrapAsync(() => { const pathUrl = this.convertPathToUrl(fpath); const url = `${this.baseUrl}/extension${pathUrl}/${encodeURIComponent(id)}`; const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 批量删除从表或从从表数据 * @param fPath 实体路径 * @param ids 要删除的实体id * @returns */ extendBatchDeleteByPath(fPath, ids) { return this.wrapAsync(() => { const pathUrl = this.convertPathToUrl(fPath); const pathArray = pathUrl.split("/"); if (pathArray.length < 3) { throw Error(`根据path删除实体数据出错了。传入的path[${fPath}]格式不对`); } const url = `${this.baseUrl}/extension${pathUrl}/batch`; const body = { ids }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 删除并保存 */ deleteAndSave(id) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/delete/${id}`; const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 批量删除并保存 * @param ids * @returns */ batchDeleteAndSave(ids) { return this.wrapAsync(() => { const url = `${this.baseUrl}/batchdeleteandsave`; const body = { ids }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.POST, url, requestConfig); }); } /** * 是否有未保存变更 * @returns */ hasChanges() { return this.wrapAsync(() => { const url = `${this.baseUrl}/haschanges`; const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig, false, true); }); } /** * 批量删除实体 * @param ids 实体id数组 * @returns */ extensionBatchDeletion(ids) { return this.wrapAsync(() => { const url = `${this.baseUrl}/extension/batchdeletion`; const body = { ids }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 取消 */ cancel() { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/cancel`; const requestConfig = { headers: { "Content-Type": "application/json" } }; return this.request(HttpMethods.POST, url, requestConfig); }); } /** * 父节点分级方式新增同级 * @param id * @returns */ parentHierarchyCreateSibling(id) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/parenthierarchycreatesibling`; const body = { dataId: id }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 父节点分级方式新增子级 * @param id * @returns */ parentHierarchyCreateChildLayer(id) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/parenthierarchycreatechildlayer`; const body = { dataId: id }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 子对象父节点分级方式新增同级 * @param ids 数据id顺序列表 * @param nodes 节点编号列表 * @returns */ childNodeParentHierarchyCreateSibling(ids, nodes) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/childnodeparenthierarchycreatesibling`; const body = { ids, nodes }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 子对象父节点分级方式新增子级 * @param ids 数据id顺序列表 * @param nodes 节点编号列表 * @returns */ childNodeParentHierarchyCreateChildLayer(ids, nodes) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/childnodeparenthierarchycreatechildlayer`; const body = { ids, nodes }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 分级码分级方式新增同级 * @param id * @returns */ pathHierarchyCreateSibling(id) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/pathhierarchycreatesibling`; const body = { dataId: id }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 分级码分级方式新增子级 * @param id * @returns */ pathHierarchyCreateChildLayer(id) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/pathhierarchycreatechildlayer`; const body = { dataId: id }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 子对象分级码分级方式新增同级 * @param ids 数据id顺序列表 * @param nodes 节点编号列表 * @returns */ childNodePathHierarchyCreateSibling(ids, nodes) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/childnodepathhierarchycreatesibling`; const body = { ids, nodes }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 子对象分级码分级方式新增子级 * @param ids 数据id顺序列表 * @param nodes 节点编号列表 * @returns */ childNodePathHierarchyCreateChildLayer(ids, nodes) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/childnodepathhierarchycreatechildlayer`; const body = { ids, nodes }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 查询全部树信息 * @param id * @param virtualPropertyName * @param fullTreeType * @param loadType * @param filter * @returns */ parentIDFullTreeQuery(id, virtualPropertyName, fullTreeType, loadType, filter) { return this.wrapAsync(() => { const url = `${this.baseUrl}/service/parentidfulltreequery`; const entityFilter = this.buildEntityFilter(filter, [], 0, 0); const body = { dataId: id, isUsePagination: false, virtualPropertyName, pagination: {}, fullTreeType, loadType, filter: entityFilter }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 获取帮助数据 * @param labelId * @param nodeCode * @param queryParam * @returns */ elementhelps(labelId, nodeCode, queryParam) { return this.wrapAsync(() => { const url = `${this.baseUrl}/extension/elementhelps`; const body = { labelId, nodeCode, queryParam }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); }); } /** * 发生请求 * @param method http请求方法 * @param url 地址 * @param requestConfigs http请求配置 * @param ignoreHandlingChanges 忽略变更 * @param selfHandError 是否自己处理错误 * @param ignoreError 忽略错误 * @returns */ request(method, url, requestConfigs = {}, ignoreHandlingChanges = false, selfHandError = false, ignoreError = false) { this.setContentType(requestConfigs); const resultPromise = this.proxyExtend.extendHeaders(requestConfigs.headers).then((headers) => { requestConfigs.headers = headers; requestConfigs.observe = "response"; return this.httpClient.request(method, url, requestConfigs).then((result) => { if (ignoreHandlingChanges === true) { return result && result.body && result.body.returnValue ? result.body.returnValue : result; } const hasRequestInfo = RequestInfoUtil.hasRequestInfo(requestConfigs); return this.proxyExtend.onResponse(result, hasRequestInfo); }).catch((error) => { return this.proxyExtend.onError(error, selfHandError, ignoreError); }); }); return resultPromise; } setContentType(requestConfigs = {}) { if (requestConfigs.headers != null && (requestConfigs.headers["Content-Type"] != null || requestConfigs.headers["content-type"] != null)) { return; } const detectedContentType = this.detectContentType(requestConfigs); switch (detectedContentType) { case ContentType.NONE: break; case ContentType.JSON: requestConfigs.headers = Object.assign({}, requestConfigs.headers, { "Content-Type": "application/json" }); break; case ContentType.FORM: requestConfigs.headers = Object.assign({}, requestConfigs.headers, { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }); break; case ContentType.TEXT: requestConfigs.headers = Object.assign({}, requestConfigs.headers, { "Content-Type": "text/plain" }); break; case ContentType.BLOB: const blob = requestConfigs.body; if (blob && blob.type) { requestConfigs.headers = Object.assign({}, requestConfigs.headers, { "Content-Type": blob.type }); } break; } } detectContentType(requestConfigs = {}) { const body = requestConfigs.body || null; if (body == null) { return ContentType.NONE; } else if (body instanceof URLSearchParams) { return ContentType.FORM; } else if (body instanceof FormData) { return ContentType.FORM_DATA; } else if (body instanceof Blob) { return ContentType.BLOB; } else if (body instanceof ArrayBuffer) { return ContentType.ARRAY_BUFFER; } else if (body && typeof body === "object") { return ContentType.JSON; } else { return ContentType.TEXT; } } /** * 将路径转换为url * @param path * @returns */ convertPathToUrl(path) { const paths = path.split("/").filter((p) => p); for (let index = paths.length - 1; index >= 0; index--) { if (index % 2 === 0) { paths[index] = encodeURIComponent(paths[index]); } if (paths[index] && paths[index].endsWith("s") && index % 2 !== 0) { paths[index] = paths[index].substring(0, paths[index].length - 1).toLowerCase(); } } return "/" + paths.join("/"); } buildEntityFilter(filter, sort, pageSize, pageIndex) { if (!filter && !sort && !pageSize && !pageIndex) { return null; } if (!filter) { filter = []; } if (!sort) { sort = []; } if (filter && filter.length > 0) { filter[filter.length - 1].Relation = 0; } const entityFilter = { FilterConditions: filter, SortConditions: sort, IsUsePagination: pageSize === 0 ? false : true, Pagination: { PageIndex: pageIndex, PageSize: pageSize, PageCount: 0, TotalCount: 0 } }; return entityFilter; } wrapAsync(asyncFunction) { return new Promise((resolve, reject) => asyncFunction().then(resolve).catch(reject)); } } class BefProxyExtend { /** * 构造函数 */ constructor(repository) { __publicField(this, "frameworkSessionService"); this.repository = repository; this.frameworkSessionService = new FrameworkSessionService(); } /** * 返回结果处理 */ onResponse(response, hasRequestInfo) { this.handleResponseHeaders(response.headers); this.handleEntityChanges(response.body); this.handleVariableChange(response.body); this.clearEntityChanges(hasRequestInfo); this.clearVariableChange(hasRequestInfo); return this.handleResponseBody(response.body); } /** * 处理服务器端返回的headers数据 */ handleResponseHeaders(headers) { this.repository.sessionService.handleResponseHeaders(headers); } /** * 处理服务器端返回的Entity变更 */ handleEntityChanges(responseInfo) { const dataChanges = responseInfo && responseInfo.innerDataChange; if (!dataChanges || !Array.isArray(dataChanges) || dataChanges.length < 1) { return; } ResponseInfoUtil.handleEntityChanges(this.repository, dataChanges); } /** * 处理后端返回的变量 */ handleVariableChange(responseInfo) { if (!responseInfo || !responseInfo.innerVariableChange) { return; } ResponseInfoUtil.handleVariableChange(this.repository, responseInfo.innerVariableChange); } /** * 处理服务器端返回的的body数据 */ handleResponseBody(responseInfo) { if (responseInfo && responseInfo.hasOwnProperty("returnValue")) { return responseInfo.returnValue; } return responseInfo; } /** * 清空Entity变更 */ clearEntityChanges(hasRequestInfo) { if (!hasRequestInfo) { return; } const entityStore = this.repository.entityStore; const entityChangeHistory = entityStore.entityChangeHistory; entityChangeHistory.stageChanges(); } /** * 清空Variable变更 */ clearVariableChange(hasRequestInfo) { if (!hasRequestInfo) { return; } const variableManager = this.repository.variableManager; variableManager.clearChanges(); } /** * 错误处理 */ onError(error, selfHandError, ignoreError) { if (selfHandError) { return Promise.reject(error); } if (ignoreError) { return Promise.resolve(); } const injector = this.repository.module.getInjector(); if (!injector) { return Promise.reject(error); } const exceptionHandler = injector.get(EXCEPTION_HANDLER_TOKEN); if (!exceptionHandler) { return Promise.reject(error); } exceptionHandler.handle(error); return Promise.reject(error); } /** * 扩展Headers */ extendHeaders(headers) { const tabId = this.frameworkSessionService.tabId; const runtimeContext = {}; if (tabId) { runtimeContext.tabId = tabId; } const beBaseUri = this.repository.apiProxy.baseUrl; const moduleId = this.repository.module.getId(); const sessionIdPromise = BefSessionManager.getSessionId(moduleId, this.repository.sessionService, beBaseUri, runtimeContext).then(() => { headers = this.repository.sessionService.extendRequestHeaders(headers, runtimeContext); return headers; }); return sessionIdPromise; } /** * 扩展Body */ extendBody(body) { return RequestInfoUtil.appendRequestInfoToBody(body, this.repository); } } function toDate(argument) { const argStr = Object.prototype.toString.call(argument); if (argument instanceof Date || typeof argument === "object" && argStr === "[object Date]") { return new argument.constructor(+argument); } else if (typeof argument === "number" || argStr === "[object Number]" || typeof argument === "string" || argStr === "[object String]") { return new Date(argument); } else { return /* @__PURE__ */ new Date(NaN); } } function constructFrom(date, value) { if (date instanceof Date) { return new date.constructor(value); } else { return new Date(value); } } const millisecondsInWeek = 6048e5; const millisecondsInDay = 864e5; let defaultOptions = {}; function getDefaultOptions() { return defaultOptions; } function startOfWeek(date, options) { var _a, _b, _c, _d; const defaultOptions2 = getDefaultOptions(); const weekStartsOn = (options == null ? void 0 : options.weekStartsOn) ?? ((_b = (_a = options == null ? void 0 : options.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.weekStartsOn) ?? defaultOptions2.weekStartsOn ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.weekStartsOn) ?? 0; const _date = toDate(date); const day = _date.getDay(); const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; _date.setDate(_date.getDate() - diff); _date.setHours(0, 0, 0, 0); return _date; } function startOfISOWeek(date) { return startOfWeek(date, { weekStartsOn: 1 }); } function getISOWeekYear(date) { const _date = toDate(date); const year = _date.getFullYear(); const fourthOfJanuaryOfNextYear = constructFrom(date, 0); fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear); const fourthOfJanuaryOfThisYear = constructFrom(date, 0); fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear); if (_date.getTime() >= startOfNextYear.getTime()) { return year + 1; } else if (_date.getTime() >= startOfThisYear.getTime()) { return year; } else { return year - 1; } } function startOfDay(date) { const _date = toDate(date); _date.setHours(0, 0, 0, 0); return _date; } function getTimezoneOffsetInMilliseconds(date) { const _date = toDate(date); const utcDate = new Date( Date.UTC( _date.getFullYear(), _date.getMonth(), _date.getDate(), _date.getHours(), _date.getMinutes(), _date.getSeconds(), _date.getMilliseconds() ) ); utcDate.setUTCFullYear(_date.getFullYear()); return +date - +utcDate; } function differenceInCalendarDays(dateLeft, dateRight) { const startOfDayLeft = startOfDay(dateLeft); const startOfDayRight = startOfDay(dateRight); const timestampLeft = +startOfDayLeft - getTimezoneOffsetInMilliseconds(startOfDayLeft); const timestampRight = +startOfDayRight - getTimezoneOffsetInMilliseconds(startOfDayRight); return Math.round((timestampLeft - timestampRight) / millisecondsInDay); } function startOfISOWeekYear(date) { const year = getISOWeekYear(date); const fourthOfJanuary = constructFrom(date, 0); fourthOfJanuary.setFullYear(year, 0, 4); fourthOfJanuary.setHours(0, 0, 0, 0); return startOfISOWeek(fourthOfJanuary); } function isDate(value) { return value instanceof Date || typeof value === "object" && Object.prototype.toString.call(value) === "[object Date]"; } function isValid(date) { if (!isDate(date) && typeof date !== "number") { return false; } const _date = toDate(date); return !isNaN(Number(_date)); } function startOfYear(date) { const cleanDate = toDate(date); const _date = constructFrom(date, 0); _date.setFullYear(cleanDate.getFullYear(), 0, 1); _date.setHours(0, 0, 0, 0); return _date; } const formatDistanceLocale = { lessThanXSeconds: { one: "less than a second", other: "less than {{count}} seconds" }, xSeconds: { one: "1 second", other: "{{count}} seconds" }, halfAMinute: "half a minute", lessThanXMinutes: { one: "less than a minute", other: "less than {{count}} minutes" }, xMinutes: { one: "1 minute", other: "{{count}} minutes" }, aboutXHours: { one: "about 1 hour", other: "about {{count}} hours" }, xHours: { one: "1 hour", other: "{{count}} hours" }, xDays: { one: "1 day", other: "{{count}} days" }, aboutXWeeks: { one: "about 1 week", other: "about {{count}} weeks" }, xWeeks: { one: "1 week", other: "{{count}} weeks" }, aboutXMonths: { one: "about 1 month", other: "about {{count}} months" }, xMonths: { one: "1 month", other: "{{count}} months" }, aboutXYears: { one: "about 1 year", other: "about {{count}} years" }, xYears: { one: "1 year", other: "{{count}} years" }, overXYears: { one: "over 1 year", other: "over {{count}} years" }, almostXYears: { one: "almost 1 year", other: "almost {{count}} years" } }; const formatDistance = (token, count, options) => { let result; const tokenValue = formatDistanceLocale[token]; if (typeof tokenValue === "string") { result = tokenValue; } else if (count === 1) { result = tokenValue.one; } else { result = tokenValue.other.replace("{{count}}", count.toString()); } if (options == null ? void 0 : options.addSuffix) { if (options.comparison && options.comparison > 0) { return "in " + result; } else { return result + " ago"; } } return result; }; function buildFormatLongFn(args) { return (options = {}) => { const width = options.width ? String(options.width) : args.defaultWidth; const format2 = args.formats[width] || args.formats[args.defaultWidth]; return format2; }; } const dateFormats = { full: "EEEE, MMMM do, y", long: "MMMM do, y", medium: "MMM d, y", short: "MM/dd/yyyy" }; const timeFormats = { full: "h:mm:ss a zzzz", long: "h:mm:ss a z", medium: "h:mm:ss a", short: "h:mm a" }; const dateTimeFormats = { full: "{{date}} 'at' {{time}}", long: "{{date}} 'at' {{time}}", medium: "{{date}}, {{time}}", short: "{{date}}, {{time}}" }; const formatLong = { date: buildFormatLongFn({ formats: dateFormats, defaultWidth: "full" }), time: buildFormatLongFn({ formats: timeFormats, defaultWidth: "full" }), dateTime: buildFormatLongFn({ formats: dateTimeFormats, defaultWidth: "full" }) }; const formatRelativeLocale = { lastWeek: "'last' eeee 'at' p", yesterday: "'yesterday at' p", today: "'today at' p", tomorrow: "'tomorrow at' p", nextWeek: "eeee 'at' p", other: "P" }; const formatRelative = (token, _date, _baseDate, _options) => formatRelativeLocale[token]; function buildLocalizeFn(args) { return (value, options) => { const context = (options == null ? void 0 : options.context) ? String(options.context) : "standalone"; let valuesArray; if (context === "formatting" && args.formattingValues) { const defaultWidth = args.defaultFormattingWidth || args.defaultWidth; const width = (options == null ? void 0 : options.width) ? String(options.width) : defaultWidth; valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; } else { const defaultWidth = args.defaultWidth; const width = (options == null ? void 0 : options.width) ? String(options.width) : args.defaultWidth; valuesArray = args.values[width] || args.values[defaultWidth]; } const index = args.argumentCallback ? args.argumentCallback(value) : value; return valuesArray[index]; }; } const eraValues = { narrow: ["B", "A"], abbreviated: ["BC", "AD"], wide: ["Before Christ", "Anno Domini"] }; const quarterValues = { narrow: ["1", "2", "3", "4"], abbreviated: ["Q1", "Q2", "Q3", "Q4"], wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"] }; const monthValues = { narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], abbreviated: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], wide: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }; const dayValues = { narrow: ["S", "M", "T", "W", "T", "F", "S"], short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], wide: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] }; const dayPeriodValues = { narrow: { am: "a", pm: "p", midnight: "mi", noon: "n", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" }, abbreviated: { am: "AM", pm: "PM", midnight: "midnight", noon: "noon", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" }, wide: { am: "a.m.", pm: "p.m.", midnight: "midnight", noon: "noon", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" } }; const formattingDayPeriodValues = { narrow: { am: "a", pm: "p", midnight: "mi", noon: "n", morning: "in the morning", afternoon: "in the afternoon", evening: "in the evening", night: "at night" }, abbreviated: { am: "AM", pm: "PM", midnight: "midnight", noon: "noon", morning: "in the morning", afternoon: "in the afternoon", evening: "in the evening", night: "at night" }, wide: { am: "a.m.", pm: "p.m.", midnight: "midnight", noon: "noon", morning: "in the morning", afternoon: "in the afternoon", evening: "in the evening", night: "at night" } }; const ordinalNumber = (dirtyNumber, _options) => { const number = Number(dirtyNumber); const rem100 = number % 100; if (rem100 > 20 || rem100 < 10) { switch (rem100 % 10) { case 1: return number + "st"; case 2: return number + "nd"; case 3: return number + "rd"; } } return number + "th"; }; const localize = { ordinalNumber, era: buildLocalizeFn({ values: eraValues, defaultWidth: "wide" }), quarter: buildLocalizeFn({ values: quarterValues, defaultWidth: "wide", argumentCallback: (quarter) => quarter - 1 }), month: buildLocalizeFn({ values: monthValues, defaultWidth: "wide" }), day: buildLocalizeFn({ values: dayValues, defaultWidth: "wide" }), dayPeriod: buildLocalizeFn({ values: dayPeriodValues, defaultWidth: "wide", formattingValues: formattingDayPeriodValues, defaultFormattingWidth: "wide" }) }; function buildMatchFn(args) { return (string, options = {}) => { const width = options.width; const matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth]; const matchResult = string.match(matchPattern); if (!matchResult) { return null; } const matchedString = matchResult[0]; const parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth]; const key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString)) : ( // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type findKey(parsePatterns, (pattern) => pattern.test(matchedString)) ); let value; value = args.valueCallback ? args.valueCallback(key) : key; value = options.valueCallback ? ( // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type options.valueCallback(value) ) : value; const rest = string.slice(matchedString.length); return { value, rest }; }; } function findKey(object, predicate) { for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key) && predicate(object[key])) { return key; } } return void 0; } function findIndex(array, predicate) { for (let key = 0; key < array.length; key++) { if (predicate(array[key])) { return key; } } return void 0; } function buildMatchPatternFn(args) { return (string, options = {}) => { const matchResult = string.match(args.matchPattern); if (!matchResult) return null; const matchedString = matchResult[0]; const parseResult = string.match(args.parsePattern); if (!parseResult) return null; let value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; value = options.valueCallback ? options.valueCallback(value) : value; const rest = string.slice(matchedString.length); return { value, rest }; }; } const matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; const parseOrdinalNumberPattern = /\d+/i; const matchEraPatterns = { narrow: /^(b|a)/i, abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, wide: /^(before christ|before common era|anno domini|common era)/i }; const parseEraPatterns = { any: [/^b/i, /^(a|c)/i]