初始化
This commit is contained in:
19
easyflow-ui-usercenter/app/src/api/bot.ts
Normal file
19
easyflow-ui-usercenter/app/src/api/bot.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { BotInfo } from '@easyflow/types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
/**
|
||||
* 获取所有智能体
|
||||
*/
|
||||
export async function getBotList() {
|
||||
return requestClient.get<BotInfo[]>('/api/v1/bot/list');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取智能体信息
|
||||
*/
|
||||
export async function getBotDetail(id: string) {
|
||||
return requestClient.get<BotInfo>('/api/v1/bot/detail', {
|
||||
params: { id },
|
||||
});
|
||||
}
|
||||
55
easyflow-ui-usercenter/app/src/api/core/auth.ts
Normal file
55
easyflow-ui-usercenter/app/src/api/core/auth.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { baseRequestClient, requestClient } from '#/api/request';
|
||||
|
||||
export namespace AuthApi {
|
||||
/** 登录接口参数 */
|
||||
export interface LoginParams {
|
||||
password?: string;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
/** 登录接口返回值 */
|
||||
export interface LoginResult {
|
||||
accessToken: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface RefreshTokenResult {
|
||||
data: string;
|
||||
status: number;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录
|
||||
*/
|
||||
export async function loginApi(data: AuthApi.LoginParams) {
|
||||
return requestClient.post<AuthApi.LoginResult>(
|
||||
'/userCenter/auth/login',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新accessToken
|
||||
*/
|
||||
export async function refreshTokenApi() {
|
||||
return baseRequestClient.post<AuthApi.RefreshTokenResult>('/auth/refresh', {
|
||||
withCredentials: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
*/
|
||||
export async function logoutApi() {
|
||||
return baseRequestClient.post('/userCenter/auth/logout', {
|
||||
withCredentials: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户权限码
|
||||
*/
|
||||
export async function getAccessCodesApi() {
|
||||
return requestClient.get<string[]>('/userCenter/auth/getPermissions');
|
||||
}
|
||||
3
easyflow-ui-usercenter/app/src/api/core/index.ts
Normal file
3
easyflow-ui-usercenter/app/src/api/core/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './auth';
|
||||
export * from './menu';
|
||||
export * from './user';
|
||||
12
easyflow-ui-usercenter/app/src/api/core/menu.ts
Normal file
12
easyflow-ui-usercenter/app/src/api/core/menu.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import type { RouteRecordStringComponent } from '@easyflow/types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
/**
|
||||
* 获取用户所有菜单
|
||||
*/
|
||||
export async function getAllMenusApi() {
|
||||
return requestClient.get<RouteRecordStringComponent[]>(
|
||||
'/api/v1/sysMenu/treeV2',
|
||||
);
|
||||
}
|
||||
10
easyflow-ui-usercenter/app/src/api/core/user.ts
Normal file
10
easyflow-ui-usercenter/app/src/api/core/user.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import type { UserInfo } from '@easyflow/types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
/**
|
||||
* 获取用户信息
|
||||
*/
|
||||
export async function getUserInfoApi() {
|
||||
return requestClient.get<UserInfo>('/api/v1/sysAccount/myProfile');
|
||||
}
|
||||
2
easyflow-ui-usercenter/app/src/api/index.ts
Normal file
2
easyflow-ui-usercenter/app/src/api/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './bot';
|
||||
export * from './core';
|
||||
225
easyflow-ui-usercenter/app/src/api/request.ts
Normal file
225
easyflow-ui-usercenter/app/src/api/request.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
import type { ServerSentEventMessage } from 'fetch-event-stream';
|
||||
|
||||
/**
|
||||
* 该文件可自行根据业务逻辑进行调整
|
||||
*/
|
||||
import type { RequestClientOptions } from '@easyflow/request';
|
||||
|
||||
import { useAppConfig } from '@easyflow/hooks';
|
||||
import { preferences } from '@easyflow/preferences';
|
||||
import {
|
||||
authenticateResponseInterceptor,
|
||||
defaultResponseInterceptor,
|
||||
errorMessageResponseInterceptor,
|
||||
RequestClient,
|
||||
} from '@easyflow/request';
|
||||
import { useAccessStore } from '@easyflow/stores';
|
||||
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { events } from 'fetch-event-stream';
|
||||
|
||||
import { useAuthStore } from '#/store';
|
||||
|
||||
import { refreshTokenApi } from './core';
|
||||
|
||||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||||
|
||||
function createRequestClient(baseURL: string, options?: RequestClientOptions) {
|
||||
const client = new RequestClient({
|
||||
...options,
|
||||
baseURL,
|
||||
});
|
||||
|
||||
/**
|
||||
* 重新认证逻辑
|
||||
*/
|
||||
async function doReAuthenticate() {
|
||||
console.warn('Access token or refresh token is invalid or expired. ');
|
||||
const accessStore = useAccessStore();
|
||||
const authStore = useAuthStore();
|
||||
accessStore.setAccessToken(null);
|
||||
if (
|
||||
preferences.app.loginExpiredMode === 'modal' &&
|
||||
accessStore.isAccessChecked
|
||||
) {
|
||||
accessStore.setLoginExpired(true);
|
||||
} else {
|
||||
await authStore.logout();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新token逻辑
|
||||
*/
|
||||
async function doRefreshToken() {
|
||||
const accessStore = useAccessStore();
|
||||
const resp = await refreshTokenApi();
|
||||
const newToken = resp.data;
|
||||
accessStore.setAccessToken(newToken);
|
||||
return newToken;
|
||||
}
|
||||
|
||||
function formatToken(token: null | string) {
|
||||
return token ? `${token}` : null;
|
||||
}
|
||||
|
||||
// 请求头处理
|
||||
client.addRequestInterceptor({
|
||||
fulfilled: async (config) => {
|
||||
const accessStore = useAccessStore();
|
||||
|
||||
config.headers['easyflow-token'] = formatToken(accessStore.accessToken);
|
||||
config.headers['Accept-Language'] = preferences.app.locale;
|
||||
return config;
|
||||
},
|
||||
});
|
||||
|
||||
// 处理返回的响应数据格式
|
||||
client.addResponseInterceptor(
|
||||
defaultResponseInterceptor({
|
||||
codeField: 'errorCode',
|
||||
dataField: 'data',
|
||||
showErrorMessage: (message) => {
|
||||
ElMessage.error(message);
|
||||
},
|
||||
successCode: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
// token过期的处理
|
||||
client.addResponseInterceptor(
|
||||
authenticateResponseInterceptor({
|
||||
client,
|
||||
doReAuthenticate,
|
||||
doRefreshToken,
|
||||
enableRefreshToken: preferences.app.enableRefreshToken,
|
||||
formatToken,
|
||||
}),
|
||||
);
|
||||
|
||||
// 通用的错误处理,如果没有进入上面的错误处理逻辑,就会进入这里
|
||||
client.addResponseInterceptor(
|
||||
errorMessageResponseInterceptor((msg: string, error) => {
|
||||
// 这里可以根据业务进行定制,你可以拿到 error 内的信息进行定制化处理,根据不同的 code 做不同的提示,而不是直接使用 message.error 提示 msg
|
||||
// 当前mock接口返回的错误字段是 error 或者 message
|
||||
const responseData = error?.response?.data ?? {};
|
||||
const errorMessage = responseData?.error ?? responseData?.message ?? '';
|
||||
// 如果没有错误信息,则会根据状态码进行提示
|
||||
ElMessage.error(errorMessage || msg);
|
||||
}),
|
||||
);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
export const requestClient = createRequestClient(apiURL, {
|
||||
responseReturn: 'data',
|
||||
});
|
||||
|
||||
export const api = createRequestClient(apiURL, {
|
||||
responseReturn: 'body',
|
||||
});
|
||||
|
||||
export const baseRequestClient = new RequestClient({ baseURL: apiURL });
|
||||
|
||||
export interface SseOptions {
|
||||
onMessage?: (message: ServerSentEventMessage) => void;
|
||||
onError?: (err: any) => void;
|
||||
onFinished?: () => void;
|
||||
}
|
||||
export class SseClient {
|
||||
private controller: AbortController | null = null;
|
||||
private currentRequestId = 0;
|
||||
|
||||
abort(): void {
|
||||
if (this.controller) {
|
||||
this.controller.abort();
|
||||
this.controller = null;
|
||||
}
|
||||
}
|
||||
|
||||
isActive(): boolean {
|
||||
return this.controller !== null;
|
||||
}
|
||||
|
||||
async post(url: string, data?: any, options?: SseOptions): Promise<void> {
|
||||
// 生成唯一的请求ID
|
||||
const requestId = ++this.currentRequestId;
|
||||
const currentRequestId = requestId;
|
||||
|
||||
// 如果已有请求,先取消
|
||||
this.abort();
|
||||
|
||||
// 创建新的控制器
|
||||
const controller = new AbortController();
|
||||
this.controller = controller;
|
||||
|
||||
// 保存信号的引用到局部变量
|
||||
const signal = controller.signal;
|
||||
|
||||
try {
|
||||
const res = await fetch(apiURL + url, {
|
||||
method: 'POST',
|
||||
signal, // 使用局部变量 signal
|
||||
headers: this.getHeaders(),
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = new Error(`HTTP ${res.status}: ${res.statusText}`);
|
||||
options?.onError?.(error);
|
||||
return;
|
||||
}
|
||||
|
||||
// 在开始事件流之前检查是否还是同一个请求
|
||||
if (this.currentRequestId !== currentRequestId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const msgEvents = events(res, signal);
|
||||
|
||||
try {
|
||||
for await (const event of msgEvents) {
|
||||
// 每次迭代都检查是否还是同一个请求
|
||||
if (this.currentRequestId !== currentRequestId) {
|
||||
break;
|
||||
}
|
||||
options?.onMessage?.(event);
|
||||
}
|
||||
} catch (innerError: any) {
|
||||
if (innerError.name !== 'AbortError') {
|
||||
options?.onError?.(innerError);
|
||||
}
|
||||
}
|
||||
|
||||
// 只有在还是同一个请求的情况下才调用 onFinished
|
||||
if (this.currentRequestId === currentRequestId) {
|
||||
options?.onFinished?.();
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (this.currentRequestId !== currentRequestId) {
|
||||
return;
|
||||
}
|
||||
if (error.name !== 'AbortError') {
|
||||
console.error('SSE错误:', error);
|
||||
options?.onError?.(error);
|
||||
}
|
||||
} finally {
|
||||
// 只有当还是当前请求时才清除 controller
|
||||
if (this.currentRequestId === currentRequestId) {
|
||||
this.controller = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getHeaders() {
|
||||
const accessStore = useAccessStore();
|
||||
return {
|
||||
Accept: 'text/event-stream',
|
||||
'Content-Type': 'application/json',
|
||||
'easyflow-token': accessStore.accessToken || '',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const sseClient = new SseClient();
|
||||
Reference in New Issue
Block a user