Skip to content

Commit

Permalink
Refactoring useHttp to httpService (opentiny#886)
Browse files Browse the repository at this point in the history
* refactor/http-service
  • Loading branch information
yy-wow authored Nov 6, 2024
1 parent d158fcd commit d019814
Show file tree
Hide file tree
Showing 86 changed files with 510 additions and 1,636 deletions.
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
File renamed without changes.
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()
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'
3 changes: 2 additions & 1 deletion designer-demo/src/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { initHook, HOOK_NAME, GenerateCodeService, Breadcrumb, Media, Lang } fro
import { initPreview } from '@opentiny/tiny-engine'
import 'virtual:svg-icons-register'
import '@opentiny/tiny-engine-theme'
import { HttpService } from './composable'

const beforeAppCreate = () => {
initHook(HOOK_NAME.useEnv, import.meta.env)
Expand All @@ -23,7 +24,7 @@ initPreview({
registry: {
root: {
id: 'engine.root',
metas: [GenerateCodeService]
metas: [HttpService, GenerateCodeService]
},
config: { id: 'engine.config', theme: 'light' },
toolbars: [Breadcrumb, Media, Lang]
Expand Down
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
65 changes: 65 additions & 0 deletions packages/common/composable/http/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { defineService, META_SERVICE } from '@opentiny/tiny-engine-meta-register'
import axios from 'axios'

let http = null

const createInterceptorHandler =
(http) =>
({ data, type }) => {
if (typeof data === 'function') {
http.interceptors[type].use(data)

return
}

if (Array.isArray(data)) {
data.forEach((item) => {
if (!item) return

if (Array.isArray(item)) {
http.interceptors[type].use(...item)

return
}

if (typeof item === 'function') {
http.interceptors[type].use(item)
}
})
}
}

export default defineService({
id: META_SERVICE.Http,
type: 'MetaService',
options: {
axiosConfig: {
// axios 配置
baseURL: '',
withCredentials: false, // 跨域请求时是否需要使用凭证
headers: {} // 请求头
},
interceptors: {
// 拦截器
request: [], // 支持配置多个请求拦截器,先注册后执行
response: [] // 支持配置多个响应拦截器,先注册先执行
}
},
init: ({ options = {} }) => {
const { axiosConfig = {}, interceptors = {} } = options
const { request = [], response = [] } = interceptors

http = axios.create(axiosConfig)
const addInterceptors = createInterceptorHandler(http)
addInterceptors({ data: request, type: 'request' })
addInterceptors({ data: response, type: 'response' })
},
apis: () => ({
getHttp: () => http,
get: (...args) => http?.get(...args),
post: (...args) => http?.post(...args),
request: (...args) => http?.request(...args),
put: (...args) => http?.put(...args),
delete: (...args) => http?.delete(...args)
})
})
1 change: 1 addition & 0 deletions packages/common/composable/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { GenerateCodeService } from './generateCode'
export { default as GlobalService } from './defaultGlobalService'
export { default as HttpService } from './http'
10 changes: 5 additions & 5 deletions packages/common/js/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@
*
*/

import { useHttp } from '@opentiny/tiny-engine-http'
import { isVsCodeEnv } from './environments'
import { generateRouter, generatePage } from './vscodeGenerateFile'
import { usePage, useCanvas, useNotify } from '@opentiny/tiny-engine-meta-register'

const http = useHttp()
import { getMetaApi, META_SERVICE } from '@opentiny/tiny-engine-meta-register'

/**
* 异常情况埋点上传
Expand All @@ -27,7 +25,9 @@ export const requestEvent = (url, params) => {
return
}

return http.post(url, params).catch(() => {})
return getMetaApi(META_SERVICE.Http)
.post(url, params)
.catch(() => {})
}

/**
Expand All @@ -38,7 +38,7 @@ export const requestEvent = (url, params) => {
*
*/
export const handlePageUpdate = (pageId, params, routerChange) => {
return http
return getMetaApi(META_SERVICE.Http)
.post(`/app-center/api/pages/update/${pageId}`, params)
.then((res) => {
const { pageSettingState } = usePage()
Expand Down
Loading

0 comments on commit d019814

Please sign in to comment.