Files
IoPlot-Dash/src/lib/api.ts

232 lines
5.8 KiB
TypeScript

import axios from 'axios';
import { toast } from 'sonner';
import { getToken, clearToken } from './auth';
// Set up API base URLs
const USER_DATA_API_URL = 'http://127.0.0.1:5001';
const DATA_API_URL = 'http://127.0.0.1:5002/api';
// Create axios instances
const userDataApi = axios.create({
baseURL: USER_DATA_API_URL,
headers: {
'Content-Type': 'application/json',
},
});
const dataApi = axios.create({
baseURL: DATA_API_URL,
headers: {
'Content-Type': 'application/json',
},
});
// Add authorization interceptor for data API
dataApi.interceptors.request.use(
(config) => {
const token = getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
userDataApi.interceptors.request.use(
(config) => {
const token = getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Add response interceptor to handle unauthorized errors
const handleUnauthorized = (error: any) => {
if (error.response && error.response.status === 401) {
toast.error('Your session has expired. Please login again.');
clearToken();
// Redirect to login page
window.location.href = '/login';
}
return Promise.reject(error);
};
dataApi.interceptors.response.use((response) => response, handleUnauthorized);
userDataApi.interceptors.response.use((response) => response, handleUnauthorized);
// Auth API functions
export const registerUser = async (username: string, password: string, email: string) => {
try {
const response = await userDataApi.post('/auth/register', { username, password, email });
return response.data;
} catch (error: any) {
throw error.response?.data || { success: false, message: 'Network error' };
}
};
export const loginUser = async (username: string, password: string) => {
try {
const response = await userDataApi.post('/auth/login', { username, password });
return response.data;
} catch (error: any) {
throw error.response?.data || { success: false, message: 'Network error' };
}
};
// Data API functions
export const getAllFeeds = async () => {
try {
const response = await userDataApi.get('/api/getallfeeds');
return response.data;
} catch (error: any) {
throw error.response?.data || { success: false, message: 'Network error' };
}
};
export const addNewFeed = async (name: string, isPublic: boolean) => {
try {
const token = getToken();
if (!token) {
throw new Error("Authentication required");
}
const response = await userDataApi.post(
"/api/addnewfeed",
{
Name: name,
IsPublic: isPublic,
},
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
return response.data;
} catch (error: any) {
throw error.response?.data || { success: false, message: "Network error" };
}
};
export const updateFeed = async (feedId: string, name: string, isPublic: boolean): Promise<boolean> => {
try {
const token = getToken();
if (!token) {
throw new Error("Authentication required");
}
const response = await userDataApi.patch(
`/api/updatefeed`,
{
feedId: feedId,
Name: name,
IsPublic: isPublic,
},
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
return response.status === 200;
} catch (error: any) {
return false;
}
};
export const deleteFeed = async (feedId: string) => {
try {
const response = await userDataApi.delete('/api/deletefeed', {
data: { feedId }
});
return response.data;
} catch (error: any) {
throw error.response?.data || { success: false, message: 'Network error' };
}
};
export const getFeedDataTimeRange = async (
feedId: string,
startTime: string,
endTime: string
) => {
try {
const response = await dataApi.get(`/dash/getfeeddatatimerange/${feedId}/${startTime}/${endTime}`);
return response.data;
} catch (error: any) {
throw error.response?.data || { success: false, message: 'Network error' };
}
};
// API Key functions
export const createApiKey = async () => {
try {
const token = getToken();
if (!token) {
throw new Error('Authentication required');
}
const response = await userDataApi.get('/api/createapikey', {
headers: {
Authorization: `Bearer ${token}`
}
});
return response.data;
} catch (error: any) {
throw error.response?.data || { success: false, message: 'Network error' };
}
};
export const getUserApiKeys = async () => {
try {
const token = getToken();
if (!token) {
throw new Error('Authentication required');
}
const response = await userDataApi.get('/api/getuserapikeys', {
headers: {
Authorization: `Bearer ${token}`
}
});
return response.data;
} catch (error: any) {
throw error.response?.data || { success: false, message: 'Network error' };
}
};
export const deleteApiKey = async (ApiKey: string) => {
try {
const token = getToken();
if (!token) {
throw new Error('Authentication required');
}
const response = await userDataApi.delete('/api/deleteapikey', {
headers: {
Authorization: `Bearer ${token}`
},
data: { ApiKey }
});
return response.data;
} catch (error: any) {
throw error.response?.data || { success: false, message: 'Network error' };
}
};
export const verifyEmail = async (token: string) => {
try {
// Call the verify email endpoint with no extra headers or data
const response = await userDataApi.get(`/auth/verifyemail/${token}`);
return response.data;
} catch (error: any) {
throw error.response?.data || { success: false, message: 'Network error' };
}
};