UNPKG

@farris/bef-vue

Version:
1,735 lines (1,734 loc) 50.9 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, EntityPathNodeType, FieldType, App, EXCEPTION_HANDLER_TOKEN, HttpMethods, Repository, HttpClient, createEntitiesBySchema } 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 ChangeDetailType { } /** * 修改 */ __publicField(ChangeDetailType, "Modify", "Modify"); class BefChangeDetailBuilder { /** * 构造函数 */ constructor(repository) { /** * 实体状态 */ __publicField(this, "entityState"); this.entityState = repository.entityState; } /** * 构造后端变更集合 */ build() { const rootChengeDetails = []; const rootEntities = this.entityState.getEntities(); const entityChanges = this.entityState.entityChangeHistory.getMergedChanges(); entityChanges.forEach((entityChange) => { this.buildChangeDetail(rootChengeDetails, rootEntities, entityChange); }); return rootChengeDetails; } /** * 构造后端变更 */ buildChangeDetail(rootChangeDetails, rootEntities, entityChange) { let currentChangeDetails = rootChangeDetails; let currentEntities = rootEntities; let currentChangeDetail; let currentEntity; let parentChangeDetail; const pathNodes = entityChange.path.getNodes(); pathNodes.forEach((pathNode) => { const pathNodeType = pathNode.getNodeType(); const pathNodeValue = pathNode.getNodeValue(); if (pathNodeType === EntityPathNodeType.IdValue) { if (!Array.isArray(currentChangeDetails) || !Array.isArray(currentEntities)) { throw new Error("currentChangeDetails and currentEntities must be array"); } const entityId = pathNodeValue; currentEntity = currentEntities.find((entity) => { return entity.idValue === entityId; }) || null; if (!currentEntity) { throw new Error(`Entity(id=${entityId}) can not be found`); } currentChangeDetail = currentChangeDetails.find((changeDetail) => { return changeDetail.ChangeInfo.DataId === entityId; }) || null; if (!currentChangeDetail) { currentChangeDetail = this.createEmptyChangeDetail(entityId); currentChangeDetails.push(currentChangeDetail); } parentChangeDetail = currentChangeDetail.ChangeInfo; } else { if (!currentEntity || !currentChangeDetail) { throw new Error("currentEntity and currentChangeDetail must be array"); } const currentEntitySchema = currentEntity.getSchema(); const fieldName = pathNodeValue; const fieldSchema = currentEntitySchema.getFieldSchemaByName(fieldName); const fieldValue = currentEntity[fieldName]; if (!fieldSchema) { throw new Error(`Field(name=${fieldName}) can not be found`); } if (fieldSchema.type === FieldType.EntityList) { const childChangeDetails = currentChangeDetail.ChangeInfo[fieldName]; currentChangeDetail.ChangeInfo[fieldName] = childChangeDetails; const childEntityList = currentEntity[fieldName]; const childEntities = childEntityList.getEntities(); currentChangeDetails = childChangeDetails; currentEntities = childEntities; currentEntity = null; currentChangeDetail = null; } else if (fieldSchema.type === FieldType.Entity) { const entityFieldSchema = fieldSchema; const idKey = entityFieldSchema.entitySchema.getIdKey(); if (idKey) { let associatedChangeDetail = currentChangeDetail.ChangeInfo[fieldName]; if (!associatedChangeDetail) { associatedChangeDetail = {}; currentChangeDetail.ChangeInfo[fieldName] = associatedChangeDetail; } parentChangeDetail = associatedChangeDetail; } else { let unifiedChangeDetail = currentChangeDetail.ChangeInfo[fieldName]; if (!unifiedChangeDetail) { unifiedChangeDetail = this.createEmptyChangeDetail(); currentChangeDetail.ChangeInfo[fieldName] = unifiedChangeDetail; } parentChangeDetail = unifiedChangeDetail.ChangeInfo; } currentChangeDetails = null; currentEntities = null; currentEntity = fieldValue; } else { if (!parentChangeDetail) { throw new Error(`Field(name=${fieldName}) can not be found`); } parentChangeDetail[fieldName] = entityChange.newValue; currentChangeDetails = null; currentEntities = null; currentChangeDetail = null; currentEntity = null; parentChangeDetail = null; } } }); } /** * 创建空的ChangeDetail */ createEmptyChangeDetail(dataId) { const changeDetail = { ChangeType: ChangeDetailType.Modify, ChangeInfo: {} }; if (dataId) { changeDetail.ChangeInfo.DataId = dataId; } return changeDetail; } } class BefChangeDetailHandler { /** * 构造函数 */ constructor(repository) { /** * 实体仓库 */ __publicField(this, "repository"); /** * 实体状态 */ __publicField(this, "entityState"); this.repository = repository; this.entityState = repository.entityState; } /** * 构造后端变更集合 */ handle() { return; } } class RequestInfoUtil { /** * 构造RequestInfo */ static buildRequestInfo(repository) { const changeDetailBuilder = new BefChangeDetailBuilder(repository); const changeDetails = changeDetailBuilder.build(); const requestInfo = { dataChange: changeDetails, variableChange: null }; return requestInfo; } /** * 向body中添加RequestInfo */ static appendRequestInfoToBody(body, repository) { if (body.requestInfo) { return body; } const requestInfo = this.buildRequestInfo(repository); if (!body || Object.keys(body).length === 0) { return requestInfo; } const bodyWithRequestInfo = Object.assign({}, body, { requestInfo }); return bodyWithRequestInfo; } } class FrameworkSessionService { /** * 构造函数 */ constructor() { __publicField(this, "rtfService"); __publicField(this, "frameworkService", null); this.rtfService = this.getRuntimeFrameworkService(); } /** * 获取当前会话id */ getCurrentSessionId() { return this.formToken || "default"; } 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" } }; const frmSessionId = this.frameworkSessionId; if (frmSessionId) { 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); if (this.frameworkSessionId) { 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); if (frmSessionId) { 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 app = this.injector.get(App, void 0); if (app) { const funcInstId = app.getId(); 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 BefProxyExtend { /** * 构造函数 */ constructor(repository) { this.repository = repository; } /** * 返回结果处理 */ onResponse(response) { this.handleResponseHeaders(response.headers); return this.handleResponseBody(response.body); } /** * 处理服务器端返回的headers数据 */ handleResponseHeaders(headers) { this.repository.sessionService.handleResponseHeaders(headers); } /** * 处理服务器端返回的的body数据 */ handleResponseBody(responseInfo) { const entityState = this.repository.entityState; const entityChangeHistory = entityState.entityChangeHistory; entityChangeHistory.stageChanges(); if (responseInfo && responseInfo.hasOwnProperty("returnValue")) { return responseInfo.returnValue; } return responseInfo; } /** * 错误处理 */ onError(error, selfHandError, ignoreError) { if (selfHandError) { return Promise.reject(error); } if (ignoreError) { return Promise.resolve(); } const injector = this.repository.viewModel.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 app = this.repository.viewModel.getInjector().get(App); const tabId = app.params.get("tabId"); const runtimeContext = {}; if (tabId) { runtimeContext.tabId = tabId; } const sessionIdPromise = this.repository.sessionService.getBeSessionId(runtimeContext).then(() => { headers = this.repository.sessionService.extendRequestHeaders(headers, runtimeContext); return headers; }); return sessionIdPromise; } /** * 扩展Body */ extendBody(body) { return RequestInfoUtil.appendRequestInfoToBody(body, this.repository); } } class BefProxy { /** * 构造函数 */ constructor(httpClient) { /** * 代理扩展 */ __publicField(this, "proxyExtend"); this.httpClient = httpClient; } /** * 设置扩展策略 */ setProxyExtend(proxyExtend) { this.proxyExtend = proxyExtend; } /** * 列表数据查询(扩展) */ extendQuery(entityFilter) { 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) { 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) { 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) { 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) { const body = { 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) { 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) { 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) { 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) { const body = { changeDetails }; const bodyWithRequestInfo = this.proxyExtend.extendBody(body); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PATCH, this.baseUrl, requestConfig); } /** * 保存 */ save() { const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, this.baseUrl, requestConfig); } /** * 删除 */ extendDelete(id) { 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) { 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) { 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) { const url = `${this.baseUrl}/service/delete/${id}`; const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); } /** * 是否有未保存变更 * @returns */ hasChanges() { const url = `${this.baseUrl}/haschanges`; const bodyWithRequestInfo = this.proxyExtend.extendBody({}); const requestConfig = { body: bodyWithRequestInfo }; return this.request(HttpMethods.PUT, url, requestConfig); } /** * 批量删除实体 * @param ids 实体id数组 * @returns */ extensionBatchDeletion(ids) { 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() { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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); } /** * 发送请求 */ 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; } return this.proxyExtend.onResponse(result); }).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; } } class BefRepository extends Repository { /** * 构造函数 */ constructor(viewModel) { super(viewModel); /** * 注入器 */ __publicField(this, "injector"); /** * Bef会话管理 */ __publicField(this, "sessionService"); /** * API代理 */ __publicField(this, "apiProxy"); /** * 实体状态 */ __publicField(this, "entityState"); /** * 分页信息 */ __publicField(this, "paginationInfo", null); this.injector = viewModel.getInjector(); } /** * 初始化 */ init() { super.init(); this.initEntityState(); this.initApiProxy(); this.initSessionService(); this.initPaginationInfo(); } /** * 初始化实体状态 */ initEntityState() { this.entityState = this.viewModel.entityState; this.entitySchema = this.entityState.getEntitySchema(); this.entityType = this.entityState.getEntityType(); } /** * 初始化Proxy */ initApiProxy() { this.apiProxy = this.injector.get(this.apiProxyType); const apiProxyExtend = new BefProxyExtend(this); this.apiProxy.setProxyExtend(apiProxyExtend); } /** * 初始化SessionService */ initSessionService() { const handlingStrategyName = "SeparatedSession"; const frmSessionService = new FrameworkSessionService(); const httpClient = this.injector.get(HttpClient); const baseUrl = `${this.apiProxy.baseUrl}`; const sessionHandlingStrategyFactory = new BefSessionHandlingStrategyFactory(); const sessionHandlingStrategy = sessionHandlingStrategyFactory.create(handlingStrategyName, frmSessionService, baseUrl, httpClient, this.injector); this.sessionService = new BefSessionService(sessionHandlingStrategy); } /** * 初始化分页信息 */ initPaginationInfo() { const pagination = this.paginationInfo || {}; this.entityState.setEntityPagination(pagination); } /** * 查询实体 */ getEntities(filters, sorts, pageSize, pageIndex) { const currentPagination = this.entityState.getPaginationByPath("/"); if (currentPagination) { pageIndex = typeof pageSize === "number" ? pageIndex : currentPagination.pageIndex || 1; pageSize = typeof pageSize === "number" ? pageSize : currentPagination.pageSize || 0; } const entityFilter = this.buildEntityFilter(filters, sorts, pageSize, pageIndex); const queryPromise = this.apiProxy.filter(entityFilter).then((returnValue) => { const entityDatas = returnValue.result; const entities = this.buildEntites(entityDatas); const serverPagination = returnValue.pagination; if (serverPagination) { this.entityState.setPaginationByPath("/", serverPagination); } return entities; }); return queryPromise; } /** * 获取实体 */ getEntityById(id) { const retrievePromise = this.apiProxy.extendRetrieve(id).then((returnValue) => { const entityData = returnValue || {}; const entity = this.buildEntity(entityData); return entity; }); return retrievePromise; } /** * 加锁编辑数据 * @param id 数据id * @returns */ editEntityById(id) { const entity = this.entityState.getEntityById(id); if (!entity) { return Promise.resolve(null); } const editPromise = this.apiProxy.edit(id).then((returnValue) => { const entityData = returnValue.data; entity.loadData(entityData); return entity; }); return editPromise; } /** * 创建新实体 */ createEntity(defaultValue) { const createPromise = this.apiProxy.create(defaultValue).then((returnValue) => { const entityData = returnValue; const entity = this.buildEntity(entityData); return entity; }); return createPromise; } /** * 批量创建实体 * @param defaultValues 实体字段默认值,keyvalue格式 * @returns 实体数组 */ createEntities(defaultValues) { const createEntitiesPromise = this.apiProxy.batchCreate(defaultValues).then((returnValue) => { const entityDatas = returnValue || []; const entities = this.buildEntites(entityDatas); return entities; }); return createEntitiesPromise; } /** * 创建从表或从从表实体 * @param path 实体路径 * @param defaultValues 默认值,keyvalue格式 * @returns */ createEntityByPath(path, defaultValues) { const createEntityByPathPromise = this.apiProxy.createByPath(path, defaultValues).then((returnValue) => { const entityData = returnValue; const paths = path.split("/").filter((item) => item).filter((item, index) => index % 2 !== 0); const entityPath = this.entityState.createPath(paths); const entityListFieldSchema = this.entityState.getEntitySchema().getFieldSchemaByPath(entityPath); const entitySchema = entityListFieldSchema.entitySchema; const entities = createEntitiesBySchema(entitySchema, [entityData]); return entities.pop(); }); return createEntityByPathPromise; } /** * 批量创建从表或从从表实体 * @param path 实体路径,如/1/educations * @param defaultValues 默认值,keyvalue格式 * @returns 实体数组 */ createEntitiesByPath(path, defaultValues) { const createEntitiesByPathPromise = this.apiProxy.batchCreateByPath(path, defaultValues).then((returnValue) => { const entityDatas = returnValue || []; const paths = path.split("/").filter((item) => item).filter((item, index) => index % 2 !== 0); const entityPath = this.entityState.createPath(paths); const entityListFieldSchema = this.entityState.getEntitySchema().getFieldSchemaByPath(entityPath); const entitySchema = entityListFieldSchema.entitySchema; return createEntitiesBySchema(entitySchema, entityDatas); }); return createEntitiesByPathPromise; } /** * 删除实体 */ removeEntityById(id) { const resultPromsie = this.apiProxy.extendDelete(id).then(() => { return true; }); return resultPromsie; } /** * 批量删除仓库数据 * @param ids 实体id数组 * @returns */ removeEntitiesByIds(ids) { const removeEntitiesByIdsPromise = this.apiProxy.extensionBatchDeletion(ids).then((returnValue) => { return true; }); return removeEntitiesByIdsPromise; } /** * 删除从表或从从表实体 * @param fpath 实体路径 * @param id 实体id * @returns */ removeEntityByPath(fpath, id) { const removeEntityByPathPromise = this.apiProxy.extendDeletByPath(fpath, id).then((returnValue) => { return true; }); return removeEntityByPathPromise; } /** * 批量删除从表或从从表数据 * @param fPath 实体路径 * @param ids 实体id数组 * @returns */ removeEntitiesByPath(fPath, ids) { const removeEntitiesByPathPromise = this.apiProxy.extendBatchDeleteByPath(fPath, ids).then((returnValue) => { return true; }); return removeEntitiesByPathPromise; } /** * 删除实体 */ removeAndSaveEntityById(id) { const resultPromsie = this.apiProxy.deleteAndSave(id).then(() => { return true; }); return resultPromsie; } /** * 保存实体变更 */ saveEntityChanges() { const savePromise = this.apiProxy.save().then(() => { this.entityState.entityChangeHistory.commitChanges(); return true; }); return savePromise; } /** * 撤销实体变更 */ cancelEntityChanges() { const resultPromise = this.apiProxy.cancel().then(() => { this.entityState.entityChangeHistory.cancelChanges(); return true; }); return resultPromise; } /** * 是否有未保存的变更 * @returns */ hasChanges() { const hasChangesPromise = this.apiProxy.hasChanges().then((returnValue) => { return returnValue; }); return hasChangesPromise; } /** * 构造EntityFilter */ buildEntityFilter(filter, sort, pageSize, pageIndex) { if (!pageIndex) { pageIndex = 1; } if (!pageSize) { pageSize = 0; } const entityFilter = { FilterConditions: filter, SortConditions: sort, IsUsePagination: pageSize !== 0, Pagination: { PageIndex: pageIndex, PageSize: pageSize, PageCount: 0, TotalCount: 0 } }; return entityFilter; } } class BefTreeRepository { constructor(repository) { __publicField(this, "befRepository"); this.repository = repository; this.befRepository = repository; } } class BefParentTreeRepository extends BefTreeRepository { constructor(repository) { super(repository); this.repository = repository; } /** * 父节点分级方式新增同级 * @param id * @returns */ addSibling(id) { const apiProxy = this.befRepository.apiProxy; return apiProxy.parentHierarchyCreateSibling(id).then((returnValue) => { const entity = this.repository.buildEntity(returnValue); this.befRepository.entityState.appendEntities([entity]); return entity; }); } /** * 父节点分级方式新增子级 * @param parentId * @returns */ addChild(parentId) { const apiProxy = this.befRepository.apiProxy; return apiProxy.parentHierarchyCreateChildLayer(parentId).then((returnValue) => { const entity = this.repository.buildEntity(returnValue); this.befRepository.entityState.appendEntities([entity]); return entity; }); } } class BefPathTreeRepository extends BefTreeRepository { constructor(repository) { super(repository); this.repository = repository; } /** * 分级码分级方式新增同级 * @param id * @returns */ addSibling(id) { const apiProxy = this.befRepository.apiProxy; return apiProxy.pathHierarchyCreateSibling(id).then((returnValue) => { const entity = this.repository.buildEntity(returnValue); this.befRepository.entityState.appendEntities([entity]); return entity; }); } /** * 分级码分级方式新增子级 * @param parentId * @returns */ addChild(parentId) { const apiProxy = this.befRepository.apiProxy; return apiProxy.pathHierarchyCreateChildLayer(parentId).then((returnValue) => { const entity = this.repository.buildEntity(returnValue); this.befRepository.entityState.appendEntities([entity]); return entity; }); } } const befProviders = [ { provide: BefParentTreeRepository, useClass: BefParentTreeRepository, deps: [Repository] }, { provide: BefParentTreeRepository, useClass: BefParentTreeRepository, deps: [Repository] } ]; export { BefChangeDetailBuilder, BefChangeDetailHandler, BefEnvUtil, BefHttpUtil, BefParentTreeRepository, BefPathTreeRepository, BefProxy, BefProxyExtend, BefRepository, BefSeparatedSessionHandlingStrategy, BefSessionHandlingStrategyFactory, BefSessionService, BefTreeRepository, BefUnifiedSessionHandlingStrategy, ChangeDetailType, ContentType, FrameworkSessionService, RequestInfoUtil, SessionHandlingStrategy, SessionStorageStrategy, befProviders };