forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-client.ts
More file actions
56 lines (42 loc) · 1.46 KB
/
Copy pathapi-client.ts
File metadata and controls
56 lines (42 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import axios, { AxiosError } from 'axios';
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
let accessToken: string | null = null;
function getOrCreateCorrelationId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
return `corr-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
export const apiClient = axios.create({
baseURL: API_URL,
});
apiClient.interceptors.request.use((config) => {
config.headers = config.headers ?? {};
config.headers['X-Correlation-ID'] = getOrCreateCorrelationId();
if (accessToken != null && accessToken.length > 0) {
config.headers.Authorization = `Bearer ${accessToken}`;
}
return config;
});
export function setApiAccessToken(token: string | null): void {
accessToken = token;
}
export function extractApiErrorMessage(error: unknown): string {
if (axios.isAxiosError(error)) {
const err = error as AxiosError<{ message?: string | string[] }>;
const message = err.response?.data?.message;
if (Array.isArray(message)) {
return message.join(', ');
}
if (typeof message === 'string' && message.length > 0) {
return message;
}
if (typeof err.message === 'string' && err.message.length > 0) {
return err.message;
}
}
if (error instanceof Error && error.message.length > 0) {
return error.message;
}
return 'Something went wrong. Please try again.';
}