initHeader

This commit is contained in:
2024-08-22 11:27:06 +08:00
parent fe895bd37c
commit e0aaa7a30d
178 changed files with 5726 additions and 4999 deletions

View File

@@ -0,0 +1,2 @@
// 后端微服务模块前缀
export const PORT1 = "/admin";

View File

@@ -0,0 +1,47 @@
// ? 暂未使用,目前使用全局 Loading 来控制重复请求
import { CustomAxiosRequestConfig } from "../index";
import qs from "qs";
// 声明一个 Map 用于存储每个请求的标识 和 取消函数
let pendingMap = new Map<string, AbortController>();
// 序列化参数
export const getPendingUrl = (config: CustomAxiosRequestConfig) =>
[config.method, config.url, qs.stringify(config.data), qs.stringify(config.params)].join("&");
export class AxiosCanceler {
/**
* @description: 添加请求
* @param {Object} config
* @return void
*/
addPending(config: CustomAxiosRequestConfig) {
// 在请求开始前,对之前的请求做检查取消操作
this.removePending(config);
const url = getPendingUrl(config);
const controller = new AbortController();
config.signal = controller.signal;
pendingMap.set(url, controller);
}
/**
* @description: 移除请求
* @param {Object} config
*/
removePending(config: CustomAxiosRequestConfig) {
const url = getPendingUrl(config);
// 如果在 pending 中存在当前请求标识,需要取消当前请求
const controller = pendingMap.get(url);
controller && controller.abort();
}
/**
* @description: 清空所有pending
*/
removeAllPending() {
pendingMap.forEach(controller => {
controller && controller.abort();
});
pendingMap.clear();
}
}

View File

@@ -0,0 +1,43 @@
import { ElMessage } from "element-plus";
/**
* @description: 校验网络请求状态码
* @param {Number} status
* @return void
*/
export const checkStatus = (status: number) => {
switch (status) {
case 400:
ElMessage.error("请求失败!请您稍后重试");
break;
case 401:
ElMessage.error("登录失效!请您重新登录");
break;
case 403:
ElMessage.error("当前账号无权限访问!");
break;
case 404:
ElMessage.error("你所访问的资源不存在!");
break;
case 405:
ElMessage.error("请求方式错误!请您稍后重试");
break;
case 408:
ElMessage.error("请求超时!请您稍后重试");
break;
case 500:
ElMessage.error("服务异常!");
break;
case 502:
ElMessage.error("网关错误!");
break;
case 503:
ElMessage.error("服务不可用!");
break;
case 504:
ElMessage.error("网关超时!");
break;
default:
ElMessage.error("请求失败!");
}
};

110
frontend/src/api/index.ts Normal file
View File

@@ -0,0 +1,110 @@
import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";
import { LOGIN_URL } from "@/config";
import { ElMessage } from "element-plus";
import { ResultData } from "@/api/interface";
import { ResultEnum } from "@/enums/httpEnum";
import { checkStatus } from "./helper/checkStatus";
import { useUserStore } from "@/stores/modules/user";
import router from "@/routers";
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
loading?: boolean;
}
const config = {
// 默认地址请求地址,可在 .env.** 文件中修改
baseURL: import.meta.env.VITE_API_URL as string,
// 设置超时时间
timeout: ResultEnum.TIMEOUT as number,
// 跨域时候允许携带凭证
withCredentials: true
};
class RequestHttp {
service: AxiosInstance;
public constructor(config: AxiosRequestConfig) {
// instantiation
this.service = axios.create(config);
/**
* @description 请求拦截器
* 客户端发送请求 -> [请求拦截器] -> 服务器
* token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
*/
this.service.interceptors.request.use(
(config: CustomAxiosRequestConfig) => {
const userStore = useUserStore();
// 当前请求不需要显示 loading在 api 服务中通过指定的第三个参数: { loading: false } 来控制
config.loading ?? (config.loading = true);
config.loading && showFullScreenLoading();
if (config.headers && typeof config.headers.set === "function") {
config.headers.set("x-access-token", userStore.token);
}
return config;
},
(error: AxiosError) => {
return Promise.reject(error);
}
);
/**
* @description 响应拦截器
* 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
*/
this.service.interceptors.response.use(
(response: AxiosResponse) => {
const { data } = response;
const userStore = useUserStore();
tryHideFullScreenLoading();
// 登陆失效
if (data.code == ResultEnum.OVERDUE) {
userStore.setToken("");
router.replace(LOGIN_URL);
ElMessage.error(data.message);
return Promise.reject(data);
}
// 全局错误信息拦截(防止下载文件的时候返回数据流,没有 code 直接报错)
if (data.code && data.code !== ResultEnum.SUCCESS) {
ElMessage.error(data.message);
return Promise.reject(data);
}
// 成功请求(在页面上除非特殊情况,否则不用处理失败逻辑)
return data;
},
async (error: AxiosError) => {
const { response } = error;
tryHideFullScreenLoading();
// 请求超时 && 网络错误单独判断,没有 response
if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时!请您稍后重试");
if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误!请您稍后重试");
// 根据服务器响应的错误状态码,做不同的处理
if (response) checkStatus(response.status);
// 服务器结果都没有返回(可能服务器错误可能客户端断网),断网处理:可以跳转到断网页面
if (!window.navigator.onLine) router.replace("/500");
return Promise.reject(error);
}
);
}
/**
* @description 常用请求方法封装
*/
get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
return this.service.get(url, { params, ..._object });
}
post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
return this.service.post(url, params, _object);
}
put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
return this.service.put(url, params, _object);
}
delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
return this.service.delete(url, { params, ..._object });
}
download(url: string, params?: object, _object = {}): Promise<BlobPart> {
return this.service.post(url, params, { ..._object, responseType: "blob" });
}
}
export default new RequestHttp(config);

View File

@@ -0,0 +1,90 @@
// 请求响应参数不包含data
export interface Result {
code: string;
message: string;
}
// 请求响应参数包含data
export interface ResultData<T = any> extends Result {
data: T;
}
// 分页响应参数
export interface ResPage<T> {
list: T[];
pageNum: number;
pageSize: number;
total: number;
}
// 分页请求参数
export interface ReqPage {
pageNum: number;
pageSize: number;
}
// 文件上传模块
export namespace Upload {
export interface ResFileUrl {
fileUrl: string;
}
}
// 登录模块
export namespace Login {
export interface ReqLoginForm {
username: string;
password: string;
}
export interface ResLogin {
accessToken: string;
}
export interface ResAuthButtons {
[key: string]: string[];
}
}
// 用户管理模块
export namespace User {
export interface ReqUserParams extends ReqPage {
username: string;
gender: number;
idCard: string;
email: string;
address: string;
createTime: string[];
status: number;
}
export interface ResUserList {
id: string;
username: string;
gender: number;
user: { detail: { age: number } };
idCard: string;
email: string;
address: string;
createTime: string;
status: number;
avatar: string;
photo: any[];
children?: ResUserList[];
}
export interface ResStatus {
userLabel: string;
userValue: number;
}
export interface ResGender {
genderLabel: string;
genderValue: number;
}
export interface ResDepartment {
id: string;
name: string;
children?: ResDepartment[];
}
export interface ResRole {
id: string;
name: string;
children?: ResDepartment[];
}
}

View File

@@ -1,9 +0,0 @@
/**
* 主进程与渲染进程通信频道定义
* Definition of communication channels between main process and rendering process
*/
const ipcApiRoute = {
test: 'controller.example.test',
}
export { ipcApiRoute }

View File

@@ -0,0 +1,26 @@
import { Login } from "@/api/interface/index";
import { PORT1 } from "@/api/config/servicePort";
import http from "@/api";
/**
* @name 登录模块
*/
// 用户登录
export const loginApi = (params: Login.ReqLoginForm) => {
return http.post<Login.ResLogin>(PORT1 + `/login`, params, { loading: false }); // 正常 post json 请求 ==> application/json
};
// 获取菜单列表
export const getAuthMenuListApi = () => {
return http.get<Menu.MenuOptions[]>(PORT1 + `/menu/list`, {}, { loading: false });
};
// 获取按钮权限
export const getAuthButtonListApi = () => {
return http.get<Login.ResAuthButtons>(PORT1 + `/auth/buttons`, {}, { loading: false });
};
// 用户退出登录
export const logoutApi = () => {
return http.post(PORT1 + `/logout`);
};

View File

@@ -0,0 +1,16 @@
import { Upload } from "@/api/interface/index";
import { PORT1 } from "@/api/config/servicePort";
import http from "@/api";
/**
* @name 文件上传模块
*/
// 图片上传
export const uploadImg = (params: FormData) => {
return http.post<Upload.ResFileUrl>(PORT1 + `/file/upload/img`, params);
};
// 视频上传
export const uploadVideo = (params: FormData) => {
return http.post<Upload.ResFileUrl>(PORT1 + `/file/upload/video`, params);
};

View File

@@ -0,0 +1,71 @@
import { ResPage, User } from "@/api/interface/index";
import { PORT1 } from "@/api/config/servicePort";
import http from "@/api";
/**
* @name 用户管理模块
*/
// 获取用户列表
export const getUserList = (params: User.ReqUserParams) => {
return http.post<ResPage<User.ResUserList>>(PORT1 + `/user/list`, params);
};
// 获取树形用户列表
export const getUserTreeList = (params: User.ReqUserParams) => {
return http.post<ResPage<User.ResUserList>>(PORT1 + `/user/tree/list`, params);
};
// 新增用户
export const addUser = (params: { id: string }) => {
return http.post(PORT1 + `/user/add`, params);
};
// 批量添加用户
export const BatchAddUser = (params: FormData) => {
return http.post(PORT1 + `/user/import`, params);
};
// 编辑用户
export const editUser = (params: { id: string }) => {
return http.post(PORT1 + `/user/edit`, params);
};
// 删除用户
export const deleteUser = (params: { id: string[] }) => {
return http.post(PORT1 + `/user/delete`, params);
};
// 切换用户状态
export const changeUserStatus = (params: { id: string; status: number }) => {
return http.post(PORT1 + `/user/change`, params);
};
// 重置用户密码
export const resetUserPassWord = (params: { id: string }) => {
return http.post(PORT1 + `/user/rest_password`, params);
};
// 导出用户数据
export const exportUserInfo = (params: User.ReqUserParams) => {
return http.download(PORT1 + `/user/export`, params);
};
// 获取用户状态字典
export const getUserStatus = () => {
return http.get<User.ResStatus[]>(PORT1 + `/user/status`);
};
// 获取用户性别字典
export const getUserGender = () => {
return http.get<User.ResGender[]>(PORT1 + `/user/gender`);
};
// 获取用户部门列表
export const getUserDepartment = () => {
return http.get<User.ResDepartment[]>(PORT1 + `/user/department`);
};
// 获取用户角色字典
export const getUserRole = () => {
return http.get<User.ResRole[]>(PORT1 + `/user/role`);
};

View File

@@ -1,57 +0,0 @@
import createAxios from '@/utils/http'
import { useUserInfoStore } from '@/stores/modules/user'
import { sm3Digest } from '@/assets/commjs/sm3.js'
import { sm2, encrypt } from '@/assets/commjs/sm2.js'
// 获取公钥
export const publicKey = (params?: any) => {
if (!params) {
const userInfo = useUserInfoStore()
params = {
loginName: encrypt(userInfo.loginName),
}
}
return createAxios({
url: '/user/generateSm2Key',
method: 'get',
params,
})
}
export const pwdSm3 = async (pwd: any, loginName?: string) => {
let publicKeyStr = await publicKey(
loginName ? { loginName: encrypt(loginName) } : false,
)
let sm3Pwd = sm3Digest(pwd) //SM3加密
return sm2(sm3Pwd + '|' + pwd, publicKeyStr.data, 0)
}
//登录获取token
export const login = async (params: any) => {
params.password = await pwdSm3(params.password, params.username)
params.username = encrypt(params.username)
return createAxios({
url: '/pqs-auth/oauth/token',
method: 'post',
params,
})
}
//获取用户信息
export const getUserById = () => {
const userInfo = useUserInfoStore()
return createAxios({
url: '/user-boot/user/getUserById?id=' + userInfo.userIndex,
method: 'get',
})
}
// 刷新token
export function refreshToken(): Promise<any> {
const userInfo = useUserInfoStore()
return login({
grant_type: 'refresh_token',
refresh_token: userInfo.refresh_token,
username: userInfo.loginName,
})
}