/
opt
/
mawid
/
apps
/
dashboard
/
lib
/
/opt/mawid/apps/dashboard/lib
mkdir
upload
Name
Size
Mode
Actions
api.ts
2322
0644
edit
dl
rm
i18n.tsx
7718
0644
edit
dl
rm
Edit:
/opt/mawid/apps/dashboard/lib/api.ts
(2322B)
export const API_URL = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3001'; export const TOKEN_KEY = 'mawid_token'; export class ApiError extends Error { constructor( public status: number, message: string, ) { super(message); } } export function getToken(): string | null { return typeof window !== 'undefined' ? localStorage.getItem(TOKEN_KEY) : null; } export function setToken(token: string | null) { if (token) localStorage.setItem(TOKEN_KEY, token); else localStorage.removeItem(TOKEN_KEY); } export async function api<T>(path: string, options: RequestInit = {}): Promise<T> { const token = getToken(); const res = await fetch(`${API_URL}${path}`, { ...options, headers: { // Fastify 400s on a JSON content-type with an empty body. ...(options.body ? { 'Content-Type': 'application/json' } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(options.headers ?? {}), }, }); if (res.status === 401 && typeof window !== 'undefined' && !path.startsWith('/auth')) { setToken(null); window.location.href = '/login'; } if (!res.ok) { let message: unknown = res.statusText; try { const body = (await res.json()) as { message?: unknown }; message = body.message ?? message; } catch { // non-JSON error body } throw new ApiError(res.status, Array.isArray(message) ? message.join(', ') : String(message)); } return res.json() as Promise<T>; } /** Localized service name helper — service.name is { ar, tr, en }. */ export function serviceName(name: unknown, lang: string): string { const n = (name ?? {}) as Record<string, string>; return n[lang] ?? n.en ?? n.tr ?? Object.values(n)[0] ?? '—'; } export function formatInTz(iso: string | Date, timeZone: string, lang: string): string { return new Intl.DateTimeFormat(lang === 'ar' ? 'ar' : lang === 'tr' ? 'tr' : 'en-GB', { timeZone, weekday: 'short', day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit', hour12: false, }).format(new Date(iso)); } export function timeInTz(iso: string | Date, timeZone: string): string { return new Intl.DateTimeFormat('en-GB', { timeZone, hour: '2-digit', minute: '2-digit', hour12: false, }).format(new Date(iso)); }
Save
cmd:
run