Refactor code structure for improved readability and maintainability

This commit is contained in:
Firman Ramdhani
2026-05-22 17:53:35 +07:00
parent af0fe70ac6
commit 4260e240a0
37 changed files with 2915 additions and 74 deletions
+2 -1
View File
@@ -33,7 +33,8 @@ export default function App() {
<Route path="/403" element={<Forbidden />} />
<Route path="/maintenance" element={<Maintenance />} />
<Route path="/coming-soon" element={<ComingSoon />} />
<Route path="/" element={<Navigate to="/showcase" />} />
{/* <Route path="/" element={<Navigate to="/showcase" />} /> */}
<Route path="/" element={<Navigate to="/app" />} />
<Route path="*" element={<Navigate to="/404" />} />
</Routes>
</Suspense>
@@ -1,3 +1,10 @@
import BookingSample from "./features/booking/presentation/BookingSample";
export default function ExamplePage() {
return <div className="bg-amber-200">example</div>;
return <div className="bg-amber-200">example
<div className="p-8">
<h1 className="text-2xl font-bold mb-4">Enterprise Web App</h1>
<BookingSample />
</div>
</div>;
}
@@ -0,0 +1,43 @@
import { CommonRemoteDataServices } from '@repo/core-api/data-services';
import type { BaseEntity } from '@repo/core-api/data-services';
import { apiClient } from '../../../../../../lib/api-client';
// ─── Domain Entity ──────────────────────────────────────────────
/**
* Booking domain entity.
*
* In a real module, this would be defined in the domain layer
* (e.g., `features/booking/domain/entities.ts`) and imported here.
*/
export interface BookingEntity extends BaseEntity {
bookingCode: string;
customerName: string;
checkInDate: string;
checkOutDate: string;
status: 'pending' | 'confirmed' | 'cancelled';
totalAmount: number;
}
// ─── Data Services Instance ─────────────────────────────────────
/**
* Booking data services — wired to the enterprise `apiClient`.
*
* All requests flow through the full interceptor chain:
* Faro tracing → Bearer token injection → ApiError normalization.
*
* @example
* ```ts
* const { data } = await bookingServices.getMany({ params: { page: 1 } });
* const { data: booking } = await bookingServices.getOne('42');
* await bookingServices.confirmProcessTransaction('42');
* ```
*/
export const bookingServices = new CommonRemoteDataServices<BookingEntity>(
apiClient,
{
apiUrl: '/bookings',
moduleKey: 'BOOKING',
},
);
@@ -0,0 +1,92 @@
import { useState } from 'react';
import { bookingServices } from '../data/booking.data-services';
import type { BookingEntity } from '../data/booking.data-services';
import type { ApiResponse } from '@repo/core-api/http-client';
import { ApiError } from '@repo/core-api/errors';
/**
* Sample component demonstrating `@repo/core-api` integration
* with the advanced TelemetryContext escape hatch.
*
* Pipeline: Faro auto-instrumentation → Bearer token → GET /bookings
* + Custom span "booking.list.fetch" with enriched tags
*/
export default function BookingSample() {
const [loading, setLoading] = useState(false);
const [result, setResult] = useState<ApiResponse<BookingEntity[]> | null>(null);
const [error, setError] = useState<string | null>(null);
const handleFetch = async () => {
setLoading(true);
setError(null);
setResult(null);
try {
const response = await bookingServices.getMany<BookingEntity[]>({
params: { page: 1, limit: 20 },
// ── Telemetry Escape Hatch ──────────────────────────────
// This creates a custom OTel span named "booking.list.fetch",
// attaches business tags, and pushes a Faro event on success.
telemetryContext: {
customSpanName: 'booking.list.fetch',
tags: {
'feature': 'booking',
'ui.component': 'BookingSample',
'ui.action': 'list_fetch',
'page': 1,
},
pushEventOnSuccess: 'booking_list_loaded',
},
});
setResult(response);
console.log('[BookingSample] Response:', response);
} catch (err) {
if (err instanceof ApiError) {
setError(`[${err.code}] ${err.message} (HTTP ${err.status})`);
console.error('[BookingSample] ApiError:', err.toJSON());
} else {
setError(err instanceof Error ? err.message : 'Unknown error');
}
} finally {
setLoading(false);
}
};
return (
<div style={{ padding: 24, fontFamily: 'monospace' }}>
<h2>🧪 Booking Data Services Integration Test</h2>
<p style={{ color: '#888', fontSize: 14 }}>
Pipeline: Faro + Custom Span &quot;booking.list.fetch&quot; Bearer Token GET /bookings
</p>
<button
onClick={handleFetch}
disabled={loading}
style={{
padding: '10px 20px',
fontSize: 16,
cursor: loading ? 'wait' : 'pointer',
background: loading ? '#555' : '#4f46e5',
color: '#fff',
border: 'none',
borderRadius: 6,
marginTop: 12,
}}
>
{loading ? 'Fetching…' : 'Test Fetch Bookings'}
</button>
{error && (
<pre style={{ color: '#ef4444', marginTop: 16, whiteSpace: 'pre-wrap' }}>
{error}
</pre>
)}
{result && (
<pre style={{ marginTop: 16, background: '#1e1e2e', color: '#a6e3a1', padding: 16, borderRadius: 8, overflow: 'auto' }}>
{JSON.stringify(result, null, 2)}
</pre>
)}
</div>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { createHttpClient } from '@repo/core-api/http-client';
import { faroAdapter } from '@repo/core-api/observability';
/**
* Enterprise HTTP client for `apps/web`.
*
* - Full Faro observability via the shared `faroAdapter`
* - Automatic Bearer token injection from localStorage
* - 401 redirect to `/auth/login`
* - Supports per-request `telemetryContext` for custom spans/tags
*
* All interceptors (auth, observability, error normalization)
* are baked into this instance. Import this singleton throughout
* the web application — never create raw axios instances.
*/
export const apiClient = createHttpClient(
{
baseURL: import.meta.env.VITE_API_URL ?? 'http://localhost:8080/api/v1',
timeout: 15000,
observability: faroAdapter,
},
{
// ── Auth Interceptor ──────────────────────────────────────────
onRequest: async (config) => {
const token = localStorage.getItem('access_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
// ── Error Interceptor ─────────────────────────────────────────
onResponseError: async (error) => {
if (error.response?.status === 401) {
// Clear stale token and redirect to login
localStorage.removeItem('access_token');
window.location.href = '/auth/login';
}
throw error;
},
},
);
+14 -7
View File
@@ -1,15 +1,22 @@
// import { DateUtils } from '@repo/utils';
// import { CurrencyUtils } from '@repo/utils';
// ─── Observability Bootstrap (MUST be first) ────────────────────
// Initializes Grafana Faro + OTel auto-instrumentation before any
// React code or HTTP requests are executed.
import { initTelemetry } from '@repo/core-api/observability/setup';
initTelemetry({
appName: import.meta.env.VITE_APP_NAME || 'fe-monorepo-web',
appVersion: import.meta.env.VITE_APP_VERSION || '0.0.0',
telemetryUrl: import.meta.env.VITE_FARO_URL || 'https://telemetry.eigen.co.id/collect',
otlpTraceUrl: import.meta.env.VITE_OTLP_TRACE_URL || 'https://telemetry.eigen.co.id/v1/traces',
environment: import.meta.env.VITE_ENV || 'development',
});
// ─── Application Bootstrap ──────────────────────────────────────
import './main.css';
import { lazy, StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
const App = lazy(() => import('./apps'));
// DateUtils.setGlobalConfig('Asia/Jakarta');
// DateUtils.setGlobalConfig('Asia/Makassar');
// CurrencyUtils.setGlobalPrefix('IDR ');
// CurrencyUtils.setGlobalDecimalSeparator(',');
createRoot(document.getElementById('app')!).render(
<StrictMode>
<App />