Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/CI.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ jobs:
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
components: rustfmt
- name: Check formatting
run: cargo fmt --all -- --check
Expand All @@ -34,6 +35,7 @@ jobs:
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
components: clippy
- name: Cache cargo registry
uses: actions/cache@v4
Expand All @@ -55,6 +57,8 @@ jobs:
- uses: actions/checkout@v4
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
- name: Cache cargo registry
uses: actions/cache@v4
with:
Expand All @@ -76,6 +80,8 @@ jobs:
- uses: actions/checkout@v4
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
- name: Cache cargo registry
uses: actions/cache@v4
with:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
125 changes: 53 additions & 72 deletions frontend/lib/api/assets.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { apiClient } from '@/lib/api/client';
import apiClient from '@/lib/api/client';
import {
Asset,
AssetDocument,
Expand Down Expand Up @@ -33,135 +33,116 @@ export const assetApiClient = {
limit: number;
totalPages: number;
}> {
const searchParams = new URLSearchParams();
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
searchParams.append(key, String(value));
}
});
}
const qs = searchParams.toString();
return apiClient.request<{
assets: Asset[];
total: number;
page: number;
limit: number;
totalPages: number;
}>(`/assets${qs ? `?${qs}` : ''}`);
return apiClient
.get<{
assets: Asset[];
total: number;
page: number;
limit: number;
totalPages: number;
}>('/assets', { params })
.then((res) => res.data);
},

getAsset(id: string): Promise<Asset> {
return apiClient.request<Asset>(`/assets/${id}`);
return apiClient.get<Asset>(`/assets/${id}`).then((res) => res.data);
},

getAssetHistory(id: string, filters?: AssetHistoryFilters): Promise<AssetHistoryEvent[]> {
const params = new URLSearchParams();
if (filters) {
Object.entries(filters).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
params.append(key, String(value));
}
});
}
const qs = params.toString();
return apiClient.request<AssetHistoryEvent[]>(
`/assets/${id}/history${qs ? `?${qs}` : ''}`
);
return apiClient
.get<AssetHistoryEvent[]>(`/assets/${id}/history`, { params: filters })
.then((res) => res.data);
},

getAssetDocuments(id: string): Promise<AssetDocument[]> {
return apiClient.request<AssetDocument[]>(`/assets/${id}/documents`);
return apiClient
.get<AssetDocument[]>(`/assets/${id}/documents`)
.then((res) => res.data);
},

getMaintenanceRecords(id: string): Promise<MaintenanceRecord[]> {
return apiClient.request<MaintenanceRecord[]>(`/assets/${id}/maintenance`);
return apiClient
.get<MaintenanceRecord[]>(`/assets/${id}/maintenance`)
.then((res) => res.data);
},

getAssetNotes(id: string): Promise<AssetNote[]> {
return apiClient.request<AssetNote[]>(`/assets/${id}/notes`);
return apiClient.get<AssetNote[]>(`/assets/${id}/notes`).then((res) => res.data);
},

getDepartments(): Promise<DepartmentWithCount[]> {
return apiClient.request<DepartmentWithCount[]>('/departments');
return apiClient
.get<DepartmentWithCount[]>('/departments')
.then((res) => res.data);
},

createDepartment(data: { name: string; description?: string }): Promise<Department> {
return apiClient.request<Department>('/departments', {
method: 'POST',
body: JSON.stringify(data),
});
return apiClient.post<Department>('/departments', data).then((res) => res.data);
},

deleteDepartment(id: string): Promise<void> {
return apiClient.request<void>(`/departments/${id}`, { method: 'DELETE' });
return apiClient.delete<void>(`/departments/${id}`).then((res) => res.data);
},

getCategories(): Promise<CategoryWithCount[]> {
return apiClient.request<CategoryWithCount[]>('/categories');
return apiClient
.get<CategoryWithCount[]>('/categories')
.then((res) => res.data);
},

createCategory(data: { name: string; description?: string }): Promise<Category> {
return apiClient.request<Category>('/categories', {
method: 'POST',
body: JSON.stringify(data),
});
return apiClient.post<Category>('/categories', data).then((res) => res.data);
},

deleteCategory(id: string): Promise<void> {
return apiClient.request<void>(`/categories/${id}`, { method: 'DELETE' });
return apiClient.delete<void>(`/categories/${id}`).then((res) => res.data);
},

getUsers(): Promise<AssetUser[]> {
return apiClient.request<AssetUser[]>('/users');
return apiClient.get<AssetUser[]>('/users').then((res) => res.data);
},

updateAssetStatus(id: string, data: UpdateAssetStatusInput): Promise<Asset> {
return apiClient.request<Asset>(`/assets/${id}/status`, {
method: 'PATCH',
body: JSON.stringify(data),
});
return apiClient
.patch<Asset>(`/assets/${id}/status`, data)
.then((res) => res.data);
},

transferAsset(id: string, data: TransferAssetInput): Promise<Asset> {
return apiClient.request<Asset>(`/assets/${id}/transfer`, {
method: 'POST',
body: JSON.stringify(data),
});
return apiClient.post<Asset>(`/assets/${id}/transfer`, data).then((res) => res.data);
},

deleteAsset(id: string): Promise<void> {
return apiClient.request<void>(`/assets/${id}`, { method: 'DELETE' });
return apiClient.delete<void>(`/assets/${id}`).then((res) => res.data);
},

uploadDocument(assetId: string, file: File, name?: string): Promise<AssetDocument> {
const form = new FormData();
form.append('file', file);
if (name) form.append('name', name);
return apiClient.request<AssetDocument>(`/assets/${assetId}/documents`, {
method: 'POST',
body: form,
headers: {},
});
return apiClient
.post<AssetDocument>(`/assets/${assetId}/documents`, form)
.then((res) => res.data);
},

deleteDocument(assetId: string, documentId: string): Promise<void> {
return apiClient.request<void>(`/assets/${assetId}/documents/${documentId}`, {
method: 'DELETE',
});
return apiClient
.delete<void>(`/assets/${assetId}/documents/${documentId}`)
.then((res) => res.data);
},

createMaintenanceRecord(assetId: string, data: CreateMaintenanceInput): Promise<MaintenanceRecord> {
return apiClient.request<MaintenanceRecord>(`/assets/${assetId}/maintenance`, {
method: 'POST',
body: JSON.stringify(data),
});
createMaintenanceRecord(
assetId: string,
data: CreateMaintenanceInput
): Promise<MaintenanceRecord> {
return apiClient
.post<MaintenanceRecord>(`/assets/${assetId}/maintenance`, data)
.then((res) => res.data);
},

createNote(assetId: string, data: CreateNoteInput): Promise<AssetNote> {
return apiClient.request<AssetNote>(`/assets/${assetId}/notes`, {
method: 'POST',
body: JSON.stringify(data),
});
return apiClient
.post<AssetNote>(`/assets/${assetId}/notes`, data)
.then((res) => res.data);
},
};
139 changes: 107 additions & 32 deletions frontend/lib/api/client.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,125 @@
import axios, { AxiosInstance, AxiosError } from 'axios';
import { RegisterInput, LoginInput, AuthResponse } from '@/lib/query/types';

const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';
const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:6003/api';

async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${BASE_URL}${path}`;

const token =
typeof window !== 'undefined' ? localStorage.getItem('token') : null;
// Separate auth client without interceptors (prevents circular refresh loops)
export const authApiClient: AxiosInstance = axios.create({
baseURL: BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});

const headers: Record<string, string> = {
// Main API client with JWT interceptors
const apiClient: AxiosInstance = axios.create({
baseURL: BASE_URL,
headers: {
'Content-Type': 'application/json',
...(options.headers as Record<string, string>),
};
},
});

if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
// Track refresh attempts to avoid infinite loops
let isRefreshing = false;
let failedQueue: Array<{
onSuccess: (token: string) => void;
onError: (error: unknown) => void;
}> = [];

const res = await fetch(url, { ...options, headers });
const processQueue = (error: unknown, token: string | null = null) => {
failedQueue.forEach((prom) => {
if (error) {
prom.onError(error);
} else {
prom.onSuccess(token || '');
}
});

if (!res.ok) {
const error = await res.json().catch(() => ({ message: res.statusText }));
throw { message: error.message ?? res.statusText, statusCode: res.status };
}
failedQueue = [];
};

if (res.status === 204) {
return undefined as T;
}
// Request interceptor: attach JWT token
apiClient.interceptors.request.use(
(config) => {
if (typeof window !== 'undefined') {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
}
return config;
},
(error) => Promise.reject(error)
);

// Response interceptor: handle 401 with refresh
apiClient.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const originalRequest = error.config as any;

return res.json() as Promise<T>;
}
if (error.response?.status === 401 && originalRequest && !originalRequest._retry) {
if (isRefreshing) {
// Queue request to retry after refresh completes
return new Promise((onSuccess, onError) => {
failedQueue.push({ onSuccess, onError });
})
.then((token) => {
originalRequest.headers.Authorization = `Bearer ${token}`;
return apiClient(originalRequest);
})
.catch((err) => Promise.reject(err));
}

originalRequest._retry = true;
isRefreshing = true;

try {
const response = await authApiClient.post<AuthResponse>('/auth/refresh');
const { accessToken } = response.data;

// Store new token
if (typeof window !== 'undefined') {
localStorage.setItem('token', accessToken);
}

// Update authorization header and retry original request
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
processQueue(null, accessToken);

return apiClient(originalRequest);
} catch (refreshError) {
processQueue(refreshError, null);
isRefreshing = false;

// Logout on refresh failure
if (typeof window !== 'undefined') {
const { useAuthStore } = await import('@/store/auth.store');
useAuthStore.getState().logout();
}

return Promise.reject(refreshError);
} finally {
isRefreshing = false;
}
}

return Promise.reject(error);
}
);

export const apiClient = {
request,
export default apiClient;

export const authApi = {
register(data: RegisterInput): Promise<AuthResponse> {
return request<AuthResponse>('/auth/register', {
method: 'POST',
body: JSON.stringify(data),
});
return authApiClient
.post<AuthResponse>('/auth/register', data)
.then((res) => res.data);
},

login(data: LoginInput): Promise<AuthResponse> {
return request<AuthResponse>('/auth/login', {
method: 'POST',
body: JSON.stringify(data),
});
return authApiClient
.post<AuthResponse>('/auth/login', data)
.then((res) => res.data);
},
};
4 changes: 2 additions & 2 deletions frontend/lib/api/reportsApi.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import api from './client';
import apiClient from './client';
import { ReportSummary } from '../users';

export async function getReportsSummary(): Promise<ReportSummary> {
const res = await api.get('/api/reports/summary');
const res = await apiClient.get('/reports/summary');
return res.data;
}
Loading
Loading