Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring useHttp to httpService #886

Merged
merged 20 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions designer-demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
"@opentiny/tiny-engine": "workspace:^",
"@opentiny/tiny-engine-theme-dark": "workspace:*",
"@opentiny/tiny-engine-theme-light": "workspace:*",
"@opentiny/tiny-engine-utils": "workspace:*",
"@opentiny/vue": "~3.14.0",
"@opentiny/vue-design-smb": "~3.14.0",
"@opentiny/vue-icon": "~3.14.0",
"@opentiny/vue-locale": "~3.14.0",
"@opentiny/vue-renderless": "~3.14.0",
"@opentiny/vue-theme": "~3.14.0",
"@vueuse/core": "^9.6.0",
"vue": "^3.4.21"
},
"devDependencies": {
Expand Down
3 changes: 2 additions & 1 deletion designer-demo/registry.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ import {
GlobalService
} from '@opentiny/tiny-engine'
import engineConfig from './engine.config'
import { HttpService } from './src/composable'

export default {
root: {
id: 'engine.root',
metas: [GenerateCodeService, GlobalService]
metas: [HttpService, GenerateCodeService, GlobalService] // GlobalService 依赖 HttpService,HttpService需要在前面处理
},
config: engineConfig,
layout: {
Expand Down
135 changes: 135 additions & 0 deletions designer-demo/src/composable/http/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { createApp } from 'vue'
import { HttpService } from '@opentiny/tiny-engine'
import { useBroadcastChannel } from '@vueuse/core'
import { constants } from '@opentiny/tiny-engine-utils'
import Login from './Login.vue'

const LOGIN_EXPIRED_CODE = 401
const { BROADCAST_CHANNEL } = constants

const { post: globalNotify } = useBroadcastChannel({ name: BROADCAST_CHANNEL.Notify })

const procession = {
promiseLogin: null,
mePromise: {}
}
let loginVM = null

const showError = (url, message) => {
globalNotify({
type: 'error',
title: '接口报错',
message: `报错接口: ${url} \n报错信息: ${message ?? ''}`
})
}

const preRequest = (config) => {
const isDevelopEnv = import.meta.env.MODE?.includes('dev')

if (isDevelopEnv && config.url.match(/\/generate\//)) {
config.baseURL = ''
}

const isVsCodeEnv = window.vscodeBridge

if (isVsCodeEnv) {
config.baseURL = ''
}

return config
}

const preResponse = (res) => {
if (res.data?.error) {
showError(res.config?.url, res?.data?.error?.message)

return Promise.reject(res.data.error)
}

return res.data?.data
}

const openLogin = () => {
if (!window.lowcode) {
const loginDom = document.createElement('div')
document.body.appendChild(loginDom)
loginVM = createApp(Login).mount(loginDom)

window.lowcode = {
platformCenter: {
Session: {
rebuiltCallback: function () {
loginVM.closeLogin()

procession.mePromise.resolve('login ok')
procession.promiseLogin = null
procession.mePromise = {}
}
}
}
}
}

return new Promise((resolve, reject) => {
if (!procession.promiseLogin) {
procession.promiseLogin = loginVM.openLogin(procession, '/api/rebuildSession')
procession.promiseLogin.then((response) => {
HttpService.apis.request(response.config).then(resolve, reject)
})
}
})
}

const errorResponse = (error) => {
// 用户信息失效时,弹窗提示登录
const { response } = error

if (response?.status === LOGIN_EXPIRED_CODE) {
// vscode 插件环境弹出输入框提示登录
if (window.vscodeBridge) {
return Promise.resolve(true)
}

// 浏览器环境弹出小窗登录
if (response?.headers['x-login-url']) {
return openLogin()
}
}

showError(error.config?.url, error?.message)

return response?.data.error ? Promise.reject(response.data.error) : Promise.reject(error.message)
}

const getConfig = (env = import.meta.env) => {
const baseURL = env.VITE_ORIGIN
// 仅在本地开发时,启用 withCredentials
const dev = env.MODE?.includes('dev')
// 获取租户 id
const getTenant = () => new URLSearchParams(location.search).get('tenant')

return {
baseURL,
withCredentials: dev,
headers: {
...(dev && { 'x-lowcode-mode': 'develop' }),
'x-lowcode-org': getTenant()
}
}
}

const customizeHttpService = () => {
const options = {
axiosConfig: getConfig(),
interceptors: {
request: [preRequest],
response: [[preResponse, errorResponse]]
}
}

HttpService.apis.setOptions(options)

return HttpService
}

export default customizeHttpService()
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2023 - present TinyEngine Authors.
* Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd.
*
* Use of this source code is governed by an MIT-style license.
*
* THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL,
* BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR
* A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
*
*/
* Copyright (c) 2023 - present TinyEngine Authors.
* Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd.
*
* Use of this source code is governed by an MIT-style license.
*
* THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL,
* BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR
* A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
*
*/

const arrData = []
const blockList = []
Expand Down Expand Up @@ -513,18 +513,10 @@ export default [
// 只有奇数区块可以保存成功
if (blockId % 2) {
const block = JSON.parse(config.data)
let blockData = null
const blockData = arrData.find((item) => Number(item.id) === Number(blockId))

for (let i = 0; i < arrData.length; i++) {
if (Number(arrData[i].id) === Number(blockId)) {
blockData = arrData[i]

Object.entries(block).forEach(([key, value]) => {
blockData[key] = value
})

break
}
if (blockData) {
Object.assign(blockData, block)
}

return new Promise((resolve) => {
Expand Down Expand Up @@ -560,18 +552,15 @@ export default [
response(config) {
const url = config.url
const blockId = url.substr(url.lastIndexOf('/') + 1)
let data = []

// 只有 ID 为奇数的区块才能删除,否则抛出错误信息
if (blockId % 2) {
arrData.some((item, index) => {
if (String(item.id) === blockId) {
data = item
arrData.splice(index, 1)
return true
}
return false
})
const index = arrData.findIndex((item) => String(item.id) === blockId)
let data = []

if (index > -1) {
data = arrData.splice(index, 1)[0]
}

return new Promise((resolve) => {
setTimeout(() => {
Expand Down Expand Up @@ -702,10 +691,11 @@ export default [
const blocks = await getAvailable()
const tags = []

blocks &&
blocks.forEach((block) => {
block.tags && tags.push(...block.tags)
})
blocks?.forEach((block) => {
if (block.tags?.length) {
tags.push(...block.tags)
}
})

return new Promise((resolve) => {
setTimeout(() => {
Expand Down Expand Up @@ -750,10 +740,9 @@ export default [
const blocks = await getAvailable()
const tenants = []

blocks &&
blocks.forEach((block) => {
block.tenant && tenants.push(block.tenant)
})
blocks?.forEach((block) => {
block.tenant && tenants.push(block.tenant)
})

return new Promise((resolve) => {
setTimeout(() => {
Expand All @@ -771,15 +760,8 @@ export default [
const params = new URLSearchParams(query)
const groupId = params.get('groups')
const value = params.get('label_contains')
let groupData = []

for (let i = 0; i < blockList.length; i++) {
if (String(blockList[i].id) === groupId) {
groupData = blockList[i].blocks

break
}
}
const group = blockList.find((item) => String(item.id) === groupId)
let groupData = group ? group.blocks : []

groupData = value ? groupData.filter((item) => item.label.indexOf(value) > -1) : groupData

Expand Down
1 change: 1 addition & 0 deletions designer-demo/src/composable/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as HttpService } from './http'
2 changes: 0 additions & 2 deletions jsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
"@opentiny/tiny-engine-theme-dark": ["packages/theme/dark/index.less"],
"@opentiny/tiny-engine-theme-light": ["packages/theme/light/index.less"],
"@opentiny/tiny-engine-svgs": ["packages/svgs/index"],
"@opentiny/tiny-engine-http": ["packages/http/index"],
"@opentiny/tiny-engine-plugin-materials/*": ["packages/plugins/materials/*"],
"@opentiny/tiny-engine-plugin-state/*": ["packages/plugins/state/*"],
"@opentiny/tiny-engine-plugin-script/*": ["packages/plugins/script/*"],
Expand All @@ -62,7 +61,6 @@
"@opentiny/tiny-engine-theme-dark/*": ["packages/theme/dark/*"],
"@opentiny/tiny-engine-theme-light/*": ["packages/theme/light/*"],
"@opentiny/tiny-engine-svgs/*": ["packages/svgs/*"],
"@opentiny/tiny-engine-http/*": ["packages/http/*"],
"@opentiny/tiny-engine-utils": ["packages/utils/src/index.js"],
"@opentiny/tiny-engine-webcomponent-core": ["packages/webcomponent/src/lib"],
"@opentiny/tiny-engine-i18n-host": ["packages/i18n/src/lib"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ const getDevAlias = (useSourceAlias) => {
'@opentiny/tiny-engine-theme-light': path.resolve(basePath, 'packages/theme/light/index.less'),
'@opentiny/tiny-engine-theme-base': path.resolve(basePath, 'packages/theme/base/src/index.js'),
'@opentiny/tiny-engine-svgs': path.resolve(basePath, 'packages/svgs/index.js'),
'@opentiny/tiny-engine-http': path.resolve(basePath, 'packages/http/src/index.js'),
'@opentiny/tiny-engine-canvas': path.resolve(basePath, 'packages/canvas/index.js'),
'@opentiny/tiny-engine-canvas/render': path.resolve(basePath, 'packages/canvas/render/index.js'),
'@opentiny/tiny-engine-utils': path.resolve(basePath, 'packages/utils/src/index.js'),
Expand Down
7 changes: 4 additions & 3 deletions packages/canvas/DesignCanvas/src/DesignCanvas.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ import {
useModal,
getMergeRegistry,
getMergeMeta,
getOptions
getOptions,
getMetaApi,
META_SERVICE
} from '@opentiny/tiny-engine-meta-register'
import { useHttp } from '@opentiny/tiny-engine-http'
import { constants } from '@opentiny/tiny-engine-utils'
import * as ast from '@opentiny/tiny-engine-common/js/ast'
import { initCanvas } from '../../init-canvas/init-canvas'
Expand Down Expand Up @@ -181,7 +182,7 @@ export default {
getMaterial: useMaterial().getMaterial,
addHistory: useHistory().addHistory,
registerBlock: useMaterial().registerBlock,
request: useHttp(),
request: getMetaApi(META_SERVICE.Http).getHttp(),
ast
},
CanvasLayout,
Expand Down
1 change: 0 additions & 1 deletion packages/canvas/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
"@babel/core": "7.18.13",
"@opentiny/tiny-engine-builtin-component": "workspace:*",
"@opentiny/tiny-engine-common": "workspace:*",
"@opentiny/tiny-engine-http": "workspace:*",
"@opentiny/tiny-engine-i18n-host": "workspace:*",
"@opentiny/tiny-engine-meta-register": "workspace:*",
"@opentiny/tiny-engine-utils": "workspace:*",
Expand Down
9 changes: 4 additions & 5 deletions packages/common/composable/defaultGlobalService.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useHttp } from '@opentiny/tiny-engine-http'
import { useMessage, useModal, defineService, META_SERVICE } from '@opentiny/tiny-engine-meta-register'
import { useMessage, useModal, defineService, getMetaApi, META_SERVICE } from '@opentiny/tiny-engine-meta-register'
import { watch } from 'vue'

const getBaseInfo = () => {
Expand Down Expand Up @@ -43,18 +42,18 @@ const initialState = {

const getUserInfo = () => {
// 获取登录用户信息
return useHttp()
return getMetaApi(META_SERVICE.Http)
.get('/platform-center/api/user/me')
.catch((error) => {
useModal().message({ message: error.message, status: 'error' })
})
}

// 获取当前应用的信息
const fetchAppInfo = (appId) => useHttp().get(`/app-center/api/apps/detail/${appId}`)
const fetchAppInfo = (appId) => getMetaApi(META_SERVICE.Http).get(`/app-center/api/apps/detail/${appId}`)

// 获取应用列表
const fetchAppList = (platformId) => useHttp().get(`/app-center/api/apps/list/${platformId}`)
const fetchAppList = (platformId) => getMetaApi(META_SERVICE.Http).get(`/app-center/api/apps/list/${platformId}`)

const { subscribe, publish } = useMessage()

Expand Down
Loading