feat(projects): @sa/axios: createRequest, createFlatRequest, createHookRequest

This commit is contained in:
Soybean
2024-01-16 01:50:12 +08:00
parent fbf4cc430d
commit bac1632457
26 changed files with 672 additions and 75 deletions

View File

@ -7,9 +7,10 @@ import { request } from '../request';
* @param password Password
*/
export function fetchLogin(userName: string, password: string) {
return request<App.Service.Response<Api.Auth.LoginToken>>('/auth/login', {
return request<Api.Auth.LoginToken>({
url: '/auth/login',
method: 'post',
body: {
data: {
userName,
password
}
@ -18,7 +19,7 @@ export function fetchLogin(userName: string, password: string) {
/** Get user info */
export function fetchGetUserInfo() {
return request<App.Service.Response<Api.Auth.UserInfo>>('/auth/getUserInfo');
return request<Api.Auth.UserInfo>({ url: '/auth/getUserInfo' });
}
/**
@ -27,10 +28,22 @@ export function fetchGetUserInfo() {
* @param refreshToken Refresh token
*/
export function fetchRefreshToken(refreshToken: string) {
return request<App.Service.Response<Api.Auth.LoginToken>>('/auth/refreshToken', {
return request<Api.Auth.LoginToken>({
url: '/auth/refreshToken',
method: 'post',
body: {
data: {
refreshToken
}
});
}
export function fetchDebug() {
return request<string>({
url: '/debug-post',
method: 'post',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: {
a: '1'
}
});
}

View File

@ -6,7 +6,7 @@ import { request } from '../request';
* @param example Whether to use example data, default: 0
*/
export function fetchGetUserRoutes(example: '0' | '1' = '0') {
return request<App.Service.Response<Api.Route.UserRoute>>('/route/getUserRoutes', { params: { example } });
return request<Api.Route.UserRoute>({ url: '/route/getUserRoutes', params: { example } });
}
/**
@ -16,5 +16,5 @@ export function fetchGetUserRoutes(example: '0' | '1' = '0') {
* @param example Whether to use example data, default: 0
*/
export function fetchIsRouteExist(routeName: string, example: '0' | '1' = '0') {
return request<App.Service.Response<boolean>>('/route/isRouteExist', { params: { routeName, example } });
return request<boolean>({ url: '/route/isRouteExist', params: { routeName, example } });
}

View File

@ -1,4 +1,4 @@
import { createOfetch as createRequest } from '@sa/request';
import { BACKEND_ERROR_CODE, createFlatRequest, createRequest } from '@sa/axios';
import { localStg } from '@/utils/storage';
import { createProxyPattern, createServiceConfig } from '~/env.config';
@ -6,20 +6,89 @@ const { baseURL, otherBaseURL } = createServiceConfig(import.meta.env);
const isHttpProxy = import.meta.env.VITE_HTTP_PROXY === 'Y';
export const request = createRequest({
baseURL: isHttpProxy ? createProxyPattern() : baseURL,
headers: {
apifoxToken: 'XL299LiMEDZ0H5h3A29PxwQXdMJqWyY2'
export const request = createFlatRequest<App.Service.Response>(
{
baseURL: isHttpProxy ? createProxyPattern() : baseURL,
headers: {
apifoxToken: 'XL299LiMEDZ0H5h3A29PxwQXdMJqWyY2'
}
},
onRequest({ options }) {
if (options.headers) {
{
async onRequest(config) {
const { headers } = config;
// set token
const token = localStg.get('token');
const Authorization = token ? `Bearer ${token}` : null;
Object.assign(headers, { Authorization });
const Authorization = token ? `Bearer ${token}` : '';
return config;
},
isBackendSuccess(response) {
// when the backend response code is "0000", it means the request is success
// you can change this logic by yourself
return response.data.code === '0000';
},
async onBackendFail(_response) {
// when the backend response code is not 200, it means the request is fail
// for example: the token is expired, refetch token and retry request
},
transformBackendResponse(response) {
return response.data.data;
},
onError(error) {
// when the request is fail, you can show error message
Object.assign(options.headers, { Authorization });
let message = error.message;
// show backend error message
if (error.code === BACKEND_ERROR_CODE) {
message = error.request?.data.msg || message;
}
window.$message?.error(message);
}
}
});
);
export const demoRequest = createRequest({ baseURL: isHttpProxy ? createProxyPattern('demo') : otherBaseURL.demo });
export const demoRequest = createRequest<App.Service.DemoResponse>(
{
baseURL: isHttpProxy ? createProxyPattern('demo') : otherBaseURL.demo
},
{
async onRequest(config) {
const { headers } = config;
// set token
const token = localStg.get('token');
const Authorization = token ? `Bearer ${token}` : null;
Object.assign(headers, { Authorization });
return config;
},
isBackendSuccess(response) {
// when the backend response code is 200, it means the request is success
// you can change this logic by yourself
return response.data.status === '200';
},
async onBackendFail(_response) {
// when the backend response code is not 200, it means the request is fail
// for example: the token is expired, refetch token and retry request
},
transformBackendResponse(response) {
return response.data.result;
},
onError(error) {
// when the request is fail, you can show error message
let message = error.message;
// show backend error message
if (error.code === BACKEND_ERROR_CODE) {
message = error.request?.data.message || message;
}
window.$message?.error(message);
}
}
);

View File

@ -45,27 +45,28 @@ export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
async function login(userName: string, password: string) {
startLoading();
try {
const { data: loginToken } = await fetchLogin(userName, password);
const { data: loginToken, error } = await fetchLogin(userName, password);
await loginByToken(loginToken);
if (!error) {
const pass = await loginByToken(loginToken);
await routeStore.initAuthRoute();
if (pass) {
await routeStore.initAuthRoute();
await redirectFromLogin();
await redirectFromLogin();
if (routeStore.isInitAuthRoute) {
window.$notification?.success({
title: $t('page.login.common.loginSuccess'),
content: $t('page.login.common.welcomeBack', { userName: userInfo.userName }),
duration: 4500
});
if (routeStore.isInitAuthRoute) {
window.$notification?.success({
title: $t('page.login.common.loginSuccess'),
content: $t('page.login.common.welcomeBack', { userName: userInfo.userName })
});
}
}
} catch {
} else {
resetStore();
} finally {
endLoading();
}
endLoading();
}
async function loginByToken(loginToken: Api.Auth.LoginToken) {
@ -73,14 +74,20 @@ export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
localStg.set('token', loginToken.token);
localStg.set('refreshToken', loginToken.refreshToken);
const { data: info } = await fetchGetUserInfo();
const { data: info, error } = await fetchGetUserInfo();
// 2. store user info
localStg.set('userInfo', info);
if (!error) {
// 2. store user info
localStg.set('userInfo', info);
// 3. update auth route
token.value = loginToken.token;
Object.assign(userInfo, info);
// 3. update auth route
token.value = loginToken.token;
Object.assign(userInfo, info);
return true;
}
return false;
}
return {

View File

@ -167,17 +167,19 @@ export const useRouteStore = defineStore(SetupStoreId.Route, () => {
/** Init dynamic auth route */
async function initDynamicAuthRoute() {
const {
data: { routes, home }
} = await fetchGetUserRoutes();
const { data, error } = await fetchGetUserRoutes();
handleAuthRoutes(routes);
if (!error) {
const { routes, home } = data;
setRouteHome(home);
handleAuthRoutes(routes);
handleUpdateRootRouteRedirect(home);
setRouteHome(home);
setIsInitAuthRoute(true);
handleUpdateRootRouteRedirect(home);
setIsInitAuthRoute(true);
}
}
/**

12
src/typings/app.d.ts vendored
View File

@ -426,9 +426,19 @@ declare namespace App {
/** The backend service response code */
code: string;
/** The backend service response message */
message: string;
msg: string;
/** The backend service response data */
data: T;
};
/** The demo backend service response data */
type DemoResponse<T = unknown> = {
/** The backend service response code */
status: string;
/** The backend service response message */
message: string;
/** The backend service response data */
result: T;
};
}
}