54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import { Query } from '@kevisual/query/query';
|
|
import { getConfig } from './get-config.ts';
|
|
import { QueryLoginNode, storage } from '@kevisual/query-login/node';
|
|
const config = getConfig();
|
|
export const baseURL = config?.baseURL || 'https://kevisual.cn';
|
|
export { storage };
|
|
export const getBaseURL = () => {
|
|
if (typeof config?.dev === 'undefined') {
|
|
return baseURL;
|
|
}
|
|
if (typeof config?.dev === 'string') {
|
|
if (config?.dev === 'true') {
|
|
return 'http://localhost:4002';
|
|
}
|
|
return baseURL;
|
|
}
|
|
if (config?.dev === true) {
|
|
return 'http://localhost:4002';
|
|
}
|
|
return baseURL;
|
|
};
|
|
export const query = new Query({
|
|
url: `${getBaseURL()}/api/router`,
|
|
});
|
|
|
|
query.beforeRequest = async (config) => {
|
|
if (config.headers) {
|
|
const token = await storage.getItem('token');
|
|
if (token) {
|
|
config.headers['Authorization'] = 'Bearer ' + token;
|
|
}
|
|
}
|
|
return config;
|
|
};
|
|
query.afterResponse = async (response, ctx) => {
|
|
if (response.code === 401) {
|
|
if (query.stop) {
|
|
return {
|
|
code: 500,
|
|
message: '登录已过期',
|
|
};
|
|
}
|
|
query.stop = true;
|
|
const res = await queryLogin.afterCheck401ToRefreshToken(response, ctx);
|
|
query.stop = false;
|
|
return res;
|
|
}
|
|
return response as any;
|
|
};
|
|
export const queryLogin = new QueryLoginNode({
|
|
query: query as any,
|
|
onLoad: async () => {},
|
|
});
|