feat: redirect login when error 401

This commit is contained in:
HYana
2025-04-28 12:25:25 +08:00
committed by Junyan Qin
parent 8d37447146
commit 3950fc39bc
+330 -281
View File
@@ -1,350 +1,399 @@
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios' import axios, {
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
AxiosError
} from "axios";
import { import {
ApiResponse, ApiRespProviderRequesters, ApiRespProviderRequester, ApiRespProviderLLMModels, ApiRespProviderRequesters,
ApiRespProviderLLMModel, LLMModel, ApiRespPipelines, ApiRespPipeline, Pipeline, ApiRespPlatformAdapters, ApiRespProviderRequester,
ApiRespPlatformAdapter, ApiRespPlatformBots, ApiRespPlatformBot, Bot, ApiRespPlugins, ApiRespPlugin, Plugin, ApiRespProviderLLMModels,
ApiRespPluginConfig, PluginReorderElement, AsyncTaskCreatedResp, ApiRespSystemInfo, ApiRespAsyncTasks, AsyncTask, ApiRespProviderLLMModel,
ApiRespAsyncTask, ApiRespUserToken LLMModel,
} from '../api/api-types' ApiRespPipelines,
import { notification } from 'antd' ApiRespPipeline,
Pipeline,
ApiRespPlatformAdapters,
ApiRespPlatformAdapter,
ApiRespPlatformBots,
ApiRespPlatformBot,
Bot,
ApiRespPlugins,
ApiRespPlugin,
ApiRespPluginConfig,
PluginReorderElement,
AsyncTaskCreatedResp,
ApiRespSystemInfo,
ApiRespAsyncTasks,
ApiRespAsyncTask,
ApiRespUserToken
} from "../api/api-types";
import { notification } from "antd";
type JSONValue = string | number | boolean | JSONObject | JSONArray | null type JSONValue = string | number | boolean | JSONObject | JSONArray | null;
interface JSONObject { [key: string]: JSONValue } interface JSONObject {
interface JSONArray extends Array<JSONValue> { } [key: string]: JSONValue;
}
type JSONArray = Array<JSONValue>;
export interface ResponseData<T = unknown> { export interface ResponseData<T = unknown> {
code: number code: number;
message: string message: string;
data: T data: T;
timestamp: number timestamp: number;
} }
export interface RequestConfig extends AxiosRequestConfig { export interface RequestConfig extends AxiosRequestConfig {
isSSR?: boolean // 服务端渲染标识 isSSR?: boolean; // 服务端渲染标识
retry?: number // 重试次数 retry?: number; // 重试次数
} }
class HttpClient { class HttpClient {
private instance: AxiosInstance private instance: AxiosInstance;
// 暂不需要SSR // 暂不需要SSR
// private ssrInstance: AxiosInstance | null = null // private ssrInstance: AxiosInstance | null = null
constructor(baseURL?: string) { constructor(baseURL?: string) {
this.instance = axios.create({ this.instance = axios.create({
baseURL: baseURL || this.getBaseUrl(), baseURL: baseURL || this.getBaseUrl(),
timeout: 15000, timeout: 15000,
headers: { headers: {
'Content-Type': 'application/json', "Content-Type": "application/json",
'X-Requested-With': 'XMLHttpRequest' "X-Requested-With": "XMLHttpRequest"
} }
}) });
this.initInterceptors() this.initInterceptors();
}
// 兜底URL,如果使用未配置会走到这里
private getBaseUrl(): string {
return "http://localhost:5300";
// NOT IMPLEMENT
if (typeof window === "undefined") {
// 服务端环境
return "";
} }
// 客户端环境
return "";
}
// 兜底URL,如果使用未配置会走到这里 // 获取Session
private getBaseUrl(): string { private async getSession() {
return "http://localhost:5300" // NOT IMPLEMENT
// NOT IMPLEMENT return "";
if (typeof window === 'undefined') { }
// 服务端环境
return "" // 同步获取Session
private getSessionSync() {
// NOT IMPLEMENT
return localStorage.getItem("token");
}
// 拦截器配置
private initInterceptors() {
// 请求拦截
this.instance.interceptors.request.use(
async (config) => {
// 服务端请求自动携带 cookie, Langbot暂时用不到SSR相关
// if (typeof window === 'undefined' && config.isSSR) { }
// cookie not required
// const { cookies } = await import('next/headers')
// config.headers.Cookie = cookies().toString()
// 客户端添加认证头
if (typeof window !== "undefined") {
const session = this.getSessionSync();
config.headers.Authorization = `Bearer ${session}`;
} }
// 客户端环境
return ""
}
// 获取Session return config;
private async getSession() { },
// NOT IMPLEMENT (error) => Promise.reject(error)
return "" );
}
// 同步获取Session // 响应拦截
private getSessionSync() { this.instance.interceptors.response.use(
// NOT IMPLEMENT (response: AxiosResponse<ResponseData>) => {
return localStorage.getItem("token") // 响应拦截处理写在这里,暂无业务需要
}
// 拦截器配置 return response;
private initInterceptors() { },
// 请求拦截 (error: AxiosError<ResponseData>) => {
this.instance.interceptors.request.use( // 统一错误处理
async (config) => { if (error.response) {
// 服务端请求自动携带 cookie, Langbot暂时用不到SSR相关 const { status, data } = error.response;
// if (typeof window === 'undefined' && config.isSSR) { } const errMessage = data?.message || error.message;
// cookie not required
// const { cookies } = await import('next/headers')
// config.headers.Cookie = cookies().toString()
// 客户端添加认证头 switch (status) {
if (typeof window !== 'undefined') { case 401:
// NOT IMPLEMENT 从本地取Session,为空跳转到登陆页 window.location.href = "/login";
// const session = await this.getSession() break;
const session = this.getSessionSync() case 403:
config.headers.Authorization = `Bearer ${session}` console.error("Permission denied:", errMessage);
} break;
case 500:
// TODO 弹Toast窗
// NOTE: move to component layer for customized message?
notification.error({
message: "服务器错误",
description: errMessage,
placement: "bottomRight"
});
console.error("Server error:", errMessage);
break;
}
return config return Promise.reject({
}, code: data?.code || status,
(error) => Promise.reject(error) message: errMessage,
) data: data?.data || null
});
// 响应拦截
this.instance.interceptors.response.use(
(response: AxiosResponse<ResponseData>) => {
// 响应拦截处理写在这里,暂无业务需要
return response
},
(error: AxiosError<ResponseData>) => {
// 统一错误处理
if (error.response) {
const { status, data } = error.response
const errMessage = data?.message || error.message
switch (status) {
case 401:
// 401 处理
break
case 403:
console.error('Permission denied:', errMessage)
break
case 500:
// TODO 弹Toast窗
// NOTE: move to component layer for customized message?
notification.error({
message: "服务器错误",
description: errMessage,
placement: "bottomRight",
})
console.error('Server error:', errMessage)
break
}
return Promise.reject({
code: data?.code || status,
message: errMessage,
data: data?.data || null
})
}
return Promise.reject({
code: -1,
message: error.message || 'Network Error',
data: null
})
}
)
}
// 转换下划线为驼峰
private convertKeysToCamel(obj: JSONValue): JSONValue {
if (Array.isArray(obj)) {
return obj.map(v => this.convertKeysToCamel(v))
} else if (obj !== null && typeof obj === 'object') {
return Object.keys(obj).reduce((acc, key) => {
const camelKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
acc[camelKey] = this.convertKeysToCamel((obj as JSONObject)[key])
return acc
}, {} as JSONObject)
} }
return obj
}
// 核心请求方法 return Promise.reject({
public async request<T = unknown>(config: RequestConfig): Promise<T> { code: -1,
try { message: error.message || "Network Error",
// 这里未来如果需要SSR可以将前面替换为SSR的instance data: null
const instance = config.isSSR ? this.instance : this.instance });
const response = await instance.request<ResponseData<T>>(config) }
return response.data.data );
} catch (error) { }
return this.handleError(error)
}
}
private handleError(error: any): never { // 转换下划线为驼峰
if (axios.isCancel(error)) { private convertKeysToCamel(obj: JSONValue): JSONValue {
throw { code: -2, message: 'Request canceled', data: null } if (Array.isArray(obj)) {
} return obj.map((v) => this.convertKeysToCamel(v));
throw error } else if (obj !== null && typeof obj === "object") {
return Object.keys(obj).reduce((acc, key) => {
const camelKey = key.replace(/_([a-z])/g, (_, letter) =>
letter.toUpperCase()
);
acc[camelKey] = this.convertKeysToCamel((obj as JSONObject)[key]);
return acc;
}, {} as JSONObject);
} }
return obj;
}
// 快捷方法 // 核心请求方法
public get<T = unknown>(url: string, params?: object, config?: RequestConfig) { public async request<T = unknown>(config: RequestConfig): Promise<T> {
return this.request<T>({ method: 'get', url, params, ...config }) try {
// 这里未来如果需要SSR可以将前面替换为SSR的instance
const instance = config.isSSR ? this.instance : this.instance;
const response = await instance.request<ResponseData<T>>(config);
return response.data.data;
} catch (error) {
return this.handleError(error as object);
} }
}
public post<T = unknown>(url: string, data?: object, config?: RequestConfig) { private handleError(error: object): never {
return this.request<T>({ method: 'post', url, data, ...config }) if (axios.isCancel(error)) {
throw { code: -2, message: "Request canceled", data: null };
} }
throw error;
}
public put<T = unknown>(url: string, data?: object, config?: RequestConfig) { // 快捷方法
return this.request<T>({ method: 'put', url, data, ...config }) public get<T = unknown>(
} url: string,
params?: object,
config?: RequestConfig
) {
return this.request<T>({ method: "get", url, params, ...config });
}
public delete<T = unknown>(url: string, config?: RequestConfig) { public post<T = unknown>(url: string, data?: object, config?: RequestConfig) {
return this.request<T>({ method: 'delete', url, ...config }) return this.request<T>({ method: "post", url, data, ...config });
} }
// real api request implementation public put<T = unknown>(url: string, data?: object, config?: RequestConfig) {
// ============ Provider API ============ return this.request<T>({ method: "put", url, data, ...config });
public getProviderRequesters(): Promise<ApiRespProviderRequesters> { }
return this.get('/api/v1/provider/requesters')
}
public getProviderRequester(name: string): Promise<ApiRespProviderRequester> { public delete<T = unknown>(url: string, config?: RequestConfig) {
return this.get(`/api/v1/provider/requesters/${name}`) return this.request<T>({ method: "delete", url, ...config });
} }
public getProviderRequesterIconURL(name: string): string { // real api request implementation
return `/api/v1/provider/requesters/${name}/icon` // ============ Provider API ============
} public getProviderRequesters(): Promise<ApiRespProviderRequesters> {
return this.get("/api/v1/provider/requesters");
}
// ============ Provider Model LLM ============ public getProviderRequester(name: string): Promise<ApiRespProviderRequester> {
public getProviderLLMModels(): Promise<ApiRespProviderLLMModels> { return this.get(`/api/v1/provider/requesters/${name}`);
return this.get('/api/v1/provider/models/llm') }
}
public getProviderLLMModel(uuid: string): Promise<ApiRespProviderLLMModel> { public getProviderRequesterIconURL(name: string): string {
return this.get(`/api/v1/provider/models/llm/${uuid}`) return `/api/v1/provider/requesters/${name}/icon`;
} }
public createProviderLLMModel(model: LLMModel): Promise<object> { // ============ Provider Model LLM ============
return this.post('/api/v1/provider/models/llm', model) public getProviderLLMModels(): Promise<ApiRespProviderLLMModels> {
} return this.get("/api/v1/provider/models/llm");
}
public deleteProviderLLMModel(uuid: string): Promise<object> { public getProviderLLMModel(uuid: string): Promise<ApiRespProviderLLMModel> {
return this.delete(`/api/v1/provider/models/llm/${uuid}`) return this.get(`/api/v1/provider/models/llm/${uuid}`);
} }
// ============ Pipeline API ============ public createProviderLLMModel(model: LLMModel): Promise<object> {
public getGeneralPipelineMetadata(): Promise<object> { // as designed, this method will be deprecated, and only for developer to check the prefered config schema return this.post("/api/v1/provider/models/llm", model);
return this.get('/api/v1/pipelines/_/metadata') }
}
public getPipelines(): Promise<ApiRespPipelines> { public deleteProviderLLMModel(uuid: string): Promise<object> {
return this.get('/api/v1/pipelines') return this.delete(`/api/v1/provider/models/llm/${uuid}`);
} }
public getPipeline(uuid: string): Promise<ApiRespPipeline> { // ============ Pipeline API ============
return this.get(`/api/v1/pipelines/${uuid}`) public getGeneralPipelineMetadata(): Promise<object> {
} // as designed, this method will be deprecated, and only for developer to check the prefered config schema
return this.get("/api/v1/pipelines/_/metadata");
}
public createPipeline(pipeline: Pipeline): Promise<object> { public getPipelines(): Promise<ApiRespPipelines> {
return this.post('/api/v1/pipelines', pipeline) return this.get("/api/v1/pipelines");
} }
public updatePipeline(uuid: string, pipeline: Pipeline): Promise<object> { public getPipeline(uuid: string): Promise<ApiRespPipeline> {
return this.put(`/api/v1/pipelines/${uuid}`, pipeline) return this.get(`/api/v1/pipelines/${uuid}`);
} }
public deletePipeline(uuid: string): Promise<object> { public createPipeline(pipeline: Pipeline): Promise<object> {
return this.delete(`/api/v1/pipelines/${uuid}`) return this.post("/api/v1/pipelines", pipeline);
} }
// ============ Platform API ============ public updatePipeline(uuid: string, pipeline: Pipeline): Promise<object> {
public getAdapters(): Promise<ApiRespPlatformAdapters> { return this.put(`/api/v1/pipelines/${uuid}`, pipeline);
return this.get('/api/v1/platform/adapters') }
}
public getAdapter(name: string): Promise<ApiRespPlatformAdapter> { public deletePipeline(uuid: string): Promise<object> {
return this.get(`/api/v1/platform/adapters/${name}`) return this.delete(`/api/v1/pipelines/${uuid}`);
} }
public getAdapterIconURL(name: string): string { // ============ Platform API ============
return `/api/v1/platform/adapters/${name}/icon` public getAdapters(): Promise<ApiRespPlatformAdapters> {
} return this.get("/api/v1/platform/adapters");
}
// ============ Platform Bots ============ public getAdapter(name: string): Promise<ApiRespPlatformAdapter> {
public getBots(): Promise<ApiRespPlatformBots> { return this.get(`/api/v1/platform/adapters/${name}`);
return this.get('/api/v1/platform/bots') }
}
public getBot(uuid: string): Promise<ApiRespPlatformBot> { public getAdapterIconURL(name: string): string {
return this.get(`/api/v1/platform/bots/${uuid}`) return `/api/v1/platform/adapters/${name}/icon`;
} }
public createBot(bot: Bot): Promise<object> { // ============ Platform Bots ============
return this.post('/api/v1/platform/bots', bot) public getBots(): Promise<ApiRespPlatformBots> {
} return this.get("/api/v1/platform/bots");
}
public updateBot(uuid: string, bot: Bot): Promise<object> { public getBot(uuid: string): Promise<ApiRespPlatformBot> {
return this.put(`/api/v1/platform/bots/${uuid}`, bot) return this.get(`/api/v1/platform/bots/${uuid}`);
} }
public deleteBot(uuid: string): Promise<object> { public createBot(bot: Bot): Promise<object> {
return this.delete(`/api/v1/platform/bots/${uuid}`) return this.post("/api/v1/platform/bots", bot);
} }
// ============ Plugins API ============ public updateBot(uuid: string, bot: Bot): Promise<object> {
public getPlugins(): Promise<ApiRespPlugins> { return this.put(`/api/v1/platform/bots/${uuid}`, bot);
return this.get('/api/v1/plugins') }
}
public getPlugin(author: string, name: string): Promise<ApiRespPlugin> { public deleteBot(uuid: string): Promise<object> {
return this.get(`/api/v1/plugins/${author}/${name}`) return this.delete(`/api/v1/platform/bots/${uuid}`);
} }
public getPluginConfig(author: string, name: string): Promise<ApiRespPluginConfig> { // ============ Plugins API ============
return this.get(`/api/v1/plugins/${author}/${name}/config`) public getPlugins(): Promise<ApiRespPlugins> {
} return this.get("/api/v1/plugins");
}
public updatePluginConfig(author: string, name: string, config: object): Promise<object> { public getPlugin(author: string, name: string): Promise<ApiRespPlugin> {
return this.put(`/api/v1/plugins/${author}/${name}/config`, config) return this.get(`/api/v1/plugins/${author}/${name}`);
} }
public togglePlugin(author: string, name: string, target_enabled: boolean): Promise<object> { public getPluginConfig(
return this.post(`/api/v1/plugins/${author}/${name}/toggle`, { target_enabled }) author: string,
} name: string
): Promise<ApiRespPluginConfig> {
return this.get(`/api/v1/plugins/${author}/${name}/config`);
}
public reorderPlugins(plugins: PluginReorderElement[]): Promise<object> { public updatePluginConfig(
return this.post('/api/v1/plugins/reorder', plugins) author: string,
} name: string,
config: object
): Promise<object> {
return this.put(`/api/v1/plugins/${author}/${name}/config`, config);
}
public updatePlugin(author: string, name: string): Promise<AsyncTaskCreatedResp> { public togglePlugin(
return this.post(`/api/v1/plugins/${author}/${name}/update`) author: string,
} name: string,
target_enabled: boolean
): Promise<object> {
return this.post(`/api/v1/plugins/${author}/${name}/toggle`, {
target_enabled
});
}
public installPluginFromGithub(source: string): Promise<AsyncTaskCreatedResp> { public reorderPlugins(plugins: PluginReorderElement[]): Promise<object> {
return this.post('/api/v1/plugins/install/github', { source }) return this.post("/api/v1/plugins/reorder", plugins);
} }
public removePlugin(author: string, name: string): Promise<AsyncTaskCreatedResp> { public updatePlugin(
return this.delete(`/api/v1/plugins/${author}/${name}`) author: string,
} name: string
): Promise<AsyncTaskCreatedResp> {
return this.post(`/api/v1/plugins/${author}/${name}/update`);
}
// ============ System API ============ public installPluginFromGithub(
public getSystemInfo(): Promise<ApiRespSystemInfo> { source: string
return this.get('/api/v1/system/info') ): Promise<AsyncTaskCreatedResp> {
} return this.post("/api/v1/plugins/install/github", { source });
}
public getAsyncTasks(): Promise<ApiRespAsyncTasks> { public removePlugin(
return this.get('/api/v1/system/tasks') author: string,
} name: string
): Promise<AsyncTaskCreatedResp> {
return this.delete(`/api/v1/plugins/${author}/${name}`);
}
public getAsyncTask(id: number): Promise<ApiRespAsyncTask> { // ============ System API ============
return this.get(`/api/v1/system/tasks/${id}`) public getSystemInfo(): Promise<ApiRespSystemInfo> {
} return this.get("/api/v1/system/info");
}
// ============ User API ============ public getAsyncTasks(): Promise<ApiRespAsyncTasks> {
public checkIfInited(): Promise<{initialized: boolean}> { return this.get("/api/v1/system/tasks");
return this.get('/api/v1/user/init') }
}
public initUser(user: string, password: string): Promise<object> { public getAsyncTask(id: number): Promise<ApiRespAsyncTask> {
return this.post('/api/v1/user/init', { user, password }) return this.get(`/api/v1/system/tasks/${id}`);
} }
public authUser(user: string, password: string): Promise<ApiRespUserToken> { // ============ User API ============
return this.post('/api/v1/user/auth', { user, password }) public checkIfInited(): Promise<{ initialized: boolean }> {
} return this.get("/api/v1/user/init");
}
public checkUserToken(): Promise<ApiRespUserToken> { public initUser(user: string, password: string): Promise<object> {
return this.get('/api/v1/user/check-token') return this.post("/api/v1/user/init", { user, password });
} }
public authUser(user: string, password: string): Promise<ApiRespUserToken> {
return this.post("/api/v1/user/auth", { user, password });
}
public checkUserToken(): Promise<ApiRespUserToken> {
return this.get("/api/v1/user/check-token");
}
} }
export const httpClient = new HttpClient("https://version-4.langbot.dev") export const httpClient = new HttpClient("https://version-4.langbot.dev");