Files
Easytier_lkddi/easytier-web/frontend-lib/src/modules/api.ts
T

178 lines
6.1 KiB
TypeScript
Raw Normal View History

2024-11-08 23:33:17 +08:00
import axios, { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
export interface ValidateConfigResponse {
toml_config: string;
}
// 定义接口返回的数据结构
export interface LoginResponse {
success: boolean;
message: string;
}
export interface RegisterResponse {
2024-11-10 11:06:58 +08:00
success: boolean;
2024-11-08 23:33:17 +08:00
message: string;
}
// 定义请求体数据结构
export interface Credential {
username: string;
password: string;
}
export interface RegisterData {
2024-11-10 11:06:58 +08:00
credentials: Credential;
2024-11-08 23:33:17 +08:00
captcha: string;
}
2024-11-10 11:06:58 +08:00
export interface Summary {
device_count: number;
}
export class ApiClient {
2024-11-08 23:33:17 +08:00
private client: AxiosInstance;
2024-11-10 11:06:58 +08:00
private authFailedCb: Function | undefined;
2024-11-08 23:33:17 +08:00
2024-11-10 11:06:58 +08:00
constructor(baseUrl: string, authFailedCb: Function | undefined = undefined) {
2024-11-08 23:33:17 +08:00
this.client = axios.create({
2024-11-10 11:06:58 +08:00
baseURL: baseUrl + '/api/v1',
2024-11-08 23:33:17 +08:00
withCredentials: true, // 如果需要支持跨域携带cookie
headers: {
'Content-Type': 'application/json',
},
});
2024-11-10 11:06:58 +08:00
this.authFailedCb = authFailedCb;
2024-11-08 23:33:17 +08:00
// 添加请求拦截器
this.client.interceptors.request.use((config: InternalAxiosRequestConfig) => {
return config;
}, (error: any) => {
return Promise.reject(error);
});
// 添加响应拦截器
this.client.interceptors.response.use((response: AxiosResponse) => {
2024-11-10 11:06:58 +08:00
console.debug('Axios Response:', response);
2024-11-08 23:33:17 +08:00
return response.data; // 假设服务器返回的数据都在data属性中
}, (error: any) => {
if (error.response) {
2024-11-10 11:06:58 +08:00
let response: AxiosResponse = error.response;
if (response.status == 401 && this.authFailedCb) {
console.error('Unauthorized:', response.data);
this.authFailedCb();
} else {
// 请求已发出,但是服务器响应的状态码不在2xx范围
console.error('Response Error:', error.response.data);
}
2024-11-08 23:33:17 +08:00
} else if (error.request) {
// 请求已发出,但是没有收到响应
console.error('Request Error:', error.request);
} else {
// 发生了一些问题导致请求未发出
console.error('Error:', error.message);
}
return Promise.reject(error);
});
}
2024-11-10 11:06:58 +08:00
// 注册
public async register(data: RegisterData): Promise<RegisterResponse> {
try {
const response = await this.client.post<RegisterResponse>('/auth/register', data);
console.log("register response:", response);
return { success: true, message: 'Register success', };
} catch (error) {
if (error instanceof AxiosError) {
return { success: false, message: 'Failed to register, error: ' + JSON.stringify(error.response?.data), };
}
return { success: false, message: 'Unknown error, error: ' + error, };
}
}
2024-11-08 23:33:17 +08:00
// 登录
public async login(data: Credential): Promise<LoginResponse> {
try {
const response = await this.client.post<any>('/auth/login', data);
console.log("login response:", response);
return { success: true, message: 'Login success', };
} catch (error) {
if (error instanceof AxiosError) {
if (error.response?.status === 401) {
return { success: false, message: 'Invalid username or password', };
} else {
return { success: false, message: 'Unknown error, status code: ' + error.response?.status, };
}
}
return { success: false, message: 'Unknown error, error: ' + error, };
}
}
2024-11-10 11:06:58 +08:00
public async logout() {
await this.client.get('/auth/logout');
if (this.authFailedCb) {
this.authFailedCb();
}
}
public async change_password(new_password: string) {
await this.client.put('/auth/password', { new_password: new_password });
}
public async check_login_status() {
try {
await this.client.get('/auth/check_login_status');
return true;
} catch (error) {
return false;
}
2024-11-08 23:33:17 +08:00
}
public async list_session() {
const response = await this.client.get('/sessions');
return response;
}
public async list_machines(): Promise<Array<any>> {
const response = await this.client.get<any, Record<string, Array<any>>>('/machines');
return response.machines;
}
public async get_network_info(machine_id: string, inst_id: string): Promise<any> {
const response = await this.client.get<any, Record<string, any>>('/machines/' + machine_id + '/networks/info/' + inst_id);
return response.info.map;
}
2024-11-10 11:06:58 +08:00
public async get_network_config(machine_id: string, inst_id: string): Promise<any> {
const response = await this.client.get<any, Record<string, any>>('/machines/' + machine_id + '/networks/config/' + inst_id);
return response;
}
2024-11-08 23:33:17 +08:00
public async validate_config(machine_id: string, config: any): Promise<ValidateConfigResponse> {
const response = await this.client.post<any, ValidateConfigResponse>(`/machines/${machine_id}/validate-config`, {
config: config,
});
return response;
}
2024-11-10 11:06:58 +08:00
public async run_network(machine_id: string, config: any): Promise<undefined> {
2024-11-08 23:33:17 +08:00
await this.client.post<string>(`/machines/${machine_id}/networks`, {
config: config,
});
}
public async delete_network(machine_id: string, inst_id: string): Promise<undefined> {
await this.client.delete<string>(`/machines/${machine_id}/networks/${inst_id}`);
}
2024-11-10 11:06:58 +08:00
public async get_summary(): Promise<Summary> {
const response = await this.client.get<any, Summary>('/summary');
return response;
}
2024-11-08 23:33:17 +08:00
public captcha_url() {
2024-11-10 11:06:58 +08:00
return this.client.defaults.baseURL + '/auth/captcha';
2024-11-08 23:33:17 +08:00
}
}
export default ApiClient;