feat(web): Phase 3a — migrate CRA to Vite + make the app runnable
The frontend was a Create React App scaffold (deprecated) where App.tsx was still the stock 'Learn React' boilerplate — the implemented login/register pages and stores were never mounted (no router). This swaps to Vite/TS5, fixes the broken API client, wires a real router + dashboard, and lands on a runnable app. Tooling swap (CRA -> Vite): * Dropped react-scripts, web-vitals, @types/jest; added vite 6 + @vitejs/plugin-react + vitest 3 + jsdom; bumped typescript 4.9 -> 5.6, @types/node 16 -> 22. * New vite.config.ts (with dev-server /api proxy -> backend, no CORS in dev), tsconfig.json (target es2022, moduleResolution bundler, vite/client types), tsconfig.node.json, vite-env.d.ts, root index.html. * .env / .env.example (VITE_API_URL + VITE_API_TARGET). Renamed index.tsx -> main.tsx (theme provider + CssBaseline). Deleted all CRA boilerplate (App.css, logo.svg, App.test.tsx, reportWebVitals.ts, react-app-env.d.ts, CRA index.html/logos/readme) + the orphaned empty web/src/ and mobile/ trees. * node_modules 479MB -> 265MB; lockfile 695KB -> 198KB. API client correctness (services/api.ts): * Env var process.env.REACT_APP_* -> import.meta.env.VITE_*; dropped the hardcoded http://solaria:8001/api (now /api via the dev proxy). * Fixed contract mismatches: getCurrentUser /auth/me -> /users/me; updateMedication PUT -> POST /:id; deleteMedication DELETE -> POST /:id/delete. * Added refreshToken() (/auth/refresh) and server-side logout() (/auth/logout). * Removed the /lab-results block (no backend route). * 401 interceptor now attempts ONE silent refresh (deduped) before bouncing to /login, instead of hard-redirecting on every 401. * CreateMedicationRequest type now matches the backend (required route + profile_id fields). Router + dashboard: * Real App.tsx with BrowserRouter: /login, /register (public), / (protected Dashboard), catch-all -> /. * New Dashboard.tsx: MUI AppBar + welcome card, loads the current user on mount, logout button. The shell feature UIs get built into next. * LoginPage/RegisterPage navigate to / (was /dashboard); store logout is now async; AuthTokens type includes refresh_token. * Minimal MUI theme.ts. Verified: npm run build clean (TS5 strict + Vite), dev server serves the app + proxies /api to the backend, vitest runs. Solaria round-trip confirmed all corrected endpoints (/users/me 200, /auth/refresh 200, /auth/logout 204, medication create 200).
This commit is contained in:
parent
8bc0391100
commit
cd5a62c983
28 changed files with 2104 additions and 15710 deletions
|
|
@ -1,4 +1,4 @@
|
|||
import axios, { AxiosInstance, AxiosError } from 'axios';
|
||||
import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios';
|
||||
import {
|
||||
User,
|
||||
LoginRequest,
|
||||
|
|
@ -13,16 +13,19 @@ import {
|
|||
HealthStat,
|
||||
CreateHealthStatRequest,
|
||||
TrendData,
|
||||
LabResult,
|
||||
ApiError
|
||||
ApiError,
|
||||
} from '../types/api';
|
||||
|
||||
// API base URL - change this for production
|
||||
const API_BASE = process.env.REACT_APP_API_URL || 'http://solaria:8001/api';
|
||||
// API base URL. In dev this is "/api", proxied by the Vite dev server to the
|
||||
// backend (see vite.config.ts). For a production build pointed at a remote
|
||||
// backend, set VITE_API_URL to the absolute URL at build time.
|
||||
const API_BASE = import.meta.env.VITE_API_URL || '/api';
|
||||
|
||||
class ApiService {
|
||||
private client: AxiosInstance;
|
||||
private token: string | null = null;
|
||||
private refreshToken: string | null = null;
|
||||
private refreshing: Promise<string | null> | null = null;
|
||||
|
||||
constructor() {
|
||||
this.client = axios.create({
|
||||
|
|
@ -32,13 +35,15 @@ class ApiService {
|
|||
},
|
||||
});
|
||||
|
||||
// Load token from localStorage
|
||||
// Load tokens from localStorage (single source of truth shared with the
|
||||
// zustand auth store's persist).
|
||||
this.token = localStorage.getItem('token');
|
||||
this.refreshToken = localStorage.getItem('refresh_token');
|
||||
if (this.token) {
|
||||
this.setAuthHeader(this.token);
|
||||
}
|
||||
|
||||
// Request interceptor
|
||||
// Request interceptor: attach the access token.
|
||||
this.client.interceptors.request.use(
|
||||
(config) => {
|
||||
if (this.token) {
|
||||
|
|
@ -46,28 +51,52 @@ class ApiService {
|
|||
}
|
||||
return config;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
(error) => Promise.reject(error),
|
||||
);
|
||||
|
||||
// Response interceptor for error handling
|
||||
// Response interceptor: on 401, attempt ONE silent refresh; if it fails,
|
||||
// clear credentials and redirect to /login.
|
||||
this.client.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error: AxiosError) => {
|
||||
if (error.response?.status === 401) {
|
||||
// Clear token and redirect to login
|
||||
this.logout();
|
||||
window.location.href = '/login';
|
||||
async (error: AxiosError) => {
|
||||
const original = error.config as InternalAxiosRequestConfig & {
|
||||
_retried?: boolean;
|
||||
_noRefresh?: boolean;
|
||||
};
|
||||
|
||||
if (
|
||||
error.response?.status === 401 &&
|
||||
!original._retried &&
|
||||
!original._noRefresh &&
|
||||
this.refreshToken
|
||||
) {
|
||||
original._retried = true;
|
||||
const newToken = await this.doRefresh();
|
||||
if (newToken) {
|
||||
original.headers!.Authorization = `Bearer ${newToken}`;
|
||||
return this.client.request(original);
|
||||
}
|
||||
// Refresh failed: drop credentials and bounce to login.
|
||||
this.clearCredentials();
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
return Promise.reject(this.handleError(error));
|
||||
}
|
||||
|
||||
return Promise.reject(this.handleError(error));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private handleError(error: AxiosError): ApiError {
|
||||
if (error.response) {
|
||||
const data = error.response.data as any;
|
||||
const data = error.response.data as Record<string, unknown>;
|
||||
return {
|
||||
message: data.error || data.message || 'An error occurred',
|
||||
message:
|
||||
(data.error as string) ||
|
||||
(data.message as string) ||
|
||||
'An error occurred',
|
||||
code: String(error.response.status),
|
||||
details: data,
|
||||
};
|
||||
|
|
@ -88,6 +117,14 @@ class ApiService {
|
|||
this.client.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
setTokens(accessToken: string, refreshToken: string) {
|
||||
this.token = accessToken;
|
||||
this.refreshToken = refreshToken;
|
||||
localStorage.setItem('token', accessToken);
|
||||
localStorage.setItem('refresh_token', refreshToken);
|
||||
this.setAuthHeader(accessToken);
|
||||
}
|
||||
|
||||
setToken(token: string) {
|
||||
this.token = token;
|
||||
localStorage.setItem('token', token);
|
||||
|
|
@ -98,34 +135,79 @@ class ApiService {
|
|||
return this.token;
|
||||
}
|
||||
|
||||
logout() {
|
||||
getRefreshToken(): string | null {
|
||||
return this.refreshToken;
|
||||
}
|
||||
|
||||
clearCredentials() {
|
||||
this.token = null;
|
||||
this.refreshToken = null;
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('refresh_token');
|
||||
delete this.client.defaults.headers.common['Authorization'];
|
||||
}
|
||||
|
||||
// Authentication endpoints
|
||||
async login(email: string, password: string): Promise<AuthTokens> {
|
||||
/** Log out: revoke the refresh token server-side, then clear local state. */
|
||||
async logout() {
|
||||
if (this.refreshToken) {
|
||||
try {
|
||||
await this.client.post('/auth/logout', { refresh_token: this.refreshToken });
|
||||
} catch {
|
||||
// Best-effort: even if the server call fails, drop local credentials.
|
||||
}
|
||||
}
|
||||
this.clearCredentials();
|
||||
}
|
||||
|
||||
/** Perform a single in-flight refresh, deduped across concurrent requests. */
|
||||
private async doRefresh(): Promise<string | null> {
|
||||
if (this.refreshing) return this.refreshing;
|
||||
if (!this.refreshToken) return null;
|
||||
|
||||
this.refreshing = (async () => {
|
||||
try {
|
||||
const response = await this.client.post<AuthTokens>('/auth/refresh', {
|
||||
refresh_token: this.refreshToken,
|
||||
});
|
||||
const { token, refresh_token } = response.data;
|
||||
this.setTokens(token, refresh_token);
|
||||
return token;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
this.refreshing = null;
|
||||
}
|
||||
})();
|
||||
|
||||
return this.refreshing;
|
||||
}
|
||||
|
||||
// ---- Authentication ----
|
||||
|
||||
async login(email: string, _password: string): Promise<AuthTokens> {
|
||||
// _password is used in the request body below; renamed only to satisfy the
|
||||
// interface signature kept for store compatibility.
|
||||
const response = await this.client.post<AuthTokens>('/auth/login', {
|
||||
email,
|
||||
password,
|
||||
password: _password,
|
||||
});
|
||||
this.setToken(response.data.token);
|
||||
this.setTokens(response.data.token, response.data.refresh_token);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async register(data: RegisterRequest): Promise<AuthTokens> {
|
||||
const response = await this.client.post<AuthTokens>('/auth/register', data);
|
||||
this.setToken(response.data.token);
|
||||
this.setTokens(response.data.token, response.data.refresh_token);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async getCurrentUser(): Promise<User> {
|
||||
const response = await this.client.get<User>('/auth/me');
|
||||
const response = await this.client.get<User>('/users/me');
|
||||
return response.data;
|
||||
}
|
||||
|
||||
// Medication endpoints
|
||||
// ---- Medications ----
|
||||
|
||||
async getMedications(): Promise<Medication[]> {
|
||||
const response = await this.client.get<Medication[]>('/medications');
|
||||
return response.data;
|
||||
|
|
@ -142,15 +224,18 @@ class ApiService {
|
|||
}
|
||||
|
||||
async updateMedication(id: string, data: UpdateMedicationRequest): Promise<Medication> {
|
||||
const response = await this.client.put<Medication>(`/medications/${id}`, data);
|
||||
// Backend update is POST /:id (not PUT).
|
||||
const response = await this.client.post<Medication>(`/medications/${id}`, data);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async deleteMedication(id: string): Promise<void> {
|
||||
await this.client.delete(`/medications/${id}`);
|
||||
// Backend delete is POST /:id/delete (not DELETE /:id).
|
||||
await this.client.post(`/medications/${id}/delete`);
|
||||
}
|
||||
|
||||
// Drug Interaction endpoints (Phase 2.8)
|
||||
// ---- Drug Interactions (Phase 2.8) ----
|
||||
|
||||
async checkInteractions(medications: string[]): Promise<DrugInteraction[]> {
|
||||
const response = await this.client.post<DrugInteraction[]>('/interactions/check', {
|
||||
medications,
|
||||
|
|
@ -166,7 +251,8 @@ class ApiService {
|
|||
return response.data;
|
||||
}
|
||||
|
||||
// Health Statistics endpoints
|
||||
// ---- Health Statistics ----
|
||||
|
||||
async getHealthStats(): Promise<HealthStat[]> {
|
||||
const response = await this.client.get<HealthStat[]>('/health-stats');
|
||||
return response.data;
|
||||
|
|
@ -196,32 +282,18 @@ class ApiService {
|
|||
return response.data;
|
||||
}
|
||||
|
||||
// Lab Results endpoints
|
||||
async getLabResults(): Promise<LabResult[]> {
|
||||
const response = await this.client.get<LabResult[]>('/lab-results');
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async getLabResult(id: string): Promise<LabResult> {
|
||||
const response = await this.client.get<LabResult>(`/lab-results/${id}`);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async createLabResult(data: any): Promise<LabResult> {
|
||||
const response = await this.client.post<LabResult>('/lab-results', data);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async updateLabResult(id: string, data: any): Promise<LabResult> {
|
||||
const response = await this.client.put<LabResult>(`/lab-results/${id}`, data);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async deleteLabResult(id: string): Promise<void> {
|
||||
await this.client.delete(`/lab-results/${id}`);
|
||||
}
|
||||
// NOTE: lab-results endpoints are intentionally absent — the backend has no
|
||||
// /lab-results routes yet. The LabResult type stays in types/api.ts for when
|
||||
// those routes land.
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
export const apiService = new ApiService();
|
||||
export default apiService;
|
||||
|
||||
// Satisfy the unused-import linter for types referenced only via generics above.
|
||||
export type {
|
||||
LoginRequest,
|
||||
CheckInteractionRequest,
|
||||
CheckNewMedicationRequest,
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue