@oxyhq/services 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +144 -250
  2. package/dist/backend/auth.d.ts +37 -0
  3. package/dist/backend/auth.js +81 -0
  4. package/dist/backend/index.d.ts +12 -0
  5. package/dist/backend/index.js +20 -0
  6. package/dist/backend/karma.d.ts +45 -0
  7. package/dist/backend/karma.js +83 -0
  8. package/dist/backend/users.d.ts +39 -0
  9. package/dist/backend/users.js +87 -0
  10. package/dist/backend/wallet.d.ts +29 -0
  11. package/dist/backend/wallet.js +68 -0
  12. package/dist/bundle.js +2 -0
  13. package/dist/bundle.js.LICENSE.txt +1 -0
  14. package/dist/frontend/context/OxyContext.d.ts +20 -0
  15. package/dist/frontend/context/OxyContext.js +97 -0
  16. package/dist/frontend/hooks/useAuth.d.ts +19 -0
  17. package/dist/frontend/hooks/useAuth.js +234 -0
  18. package/dist/frontend/hooks/useKarma.d.ts +27 -0
  19. package/dist/frontend/hooks/useKarma.js +187 -0
  20. package/dist/frontend/hooks/useUser.d.ts +13 -0
  21. package/dist/frontend/hooks/useUser.js +136 -0
  22. package/dist/frontend/hooks/useWallet.d.ts +14 -0
  23. package/dist/frontend/hooks/useWallet.js +174 -0
  24. package/dist/frontend/index.d.ts +6 -0
  25. package/dist/frontend/index.js +14 -0
  26. package/dist/index.d.ts +3 -28
  27. package/dist/index.js +17 -66
  28. package/dist/shared/api-client.d.ts +15 -0
  29. package/dist/shared/api-client.js +197 -0
  30. package/dist/shared/types.d.ts +135 -0
  31. package/package.json +45 -71
  32. package/dist/components/AuthBottomSheet/types.d.ts +0 -24
  33. package/dist/components/FileSelectorModal/types.d.ts +0 -35
  34. package/dist/components/FileSelectorModal/types.js +0 -2
  35. package/dist/components/SessionProvider.d.ts +0 -26
  36. package/dist/components/SessionProvider.js +0 -367
  37. package/dist/config.d.ts +0 -169
  38. package/dist/config.js +0 -115
  39. package/dist/constants.d.ts +0 -54
  40. package/dist/constants.js +0 -61
  41. package/dist/hooks/index.d.ts +0 -11
  42. package/dist/hooks/index.js +0 -23
  43. package/dist/hooks/useAuth.d.ts +0 -6
  44. package/dist/hooks/useAuth.js +0 -17
  45. package/dist/hooks/useFiles.d.ts +0 -10
  46. package/dist/hooks/useFiles.js +0 -329
  47. package/dist/hooks/useProfile.d.ts +0 -13
  48. package/dist/hooks/useProfile.js +0 -154
  49. package/dist/hooks/useSession.d.ts +0 -2
  50. package/dist/hooks/useSession.js +0 -12
  51. package/dist/hooks/useSubscription.d.ts +0 -15
  52. package/dist/hooks/useSubscription.js +0 -85
  53. package/dist/package.json +0 -71
  54. package/dist/reducers/index.d.ts +0 -8
  55. package/dist/reducers/index.js +0 -29
  56. package/dist/reducers/profileReducer.d.ts +0 -55
  57. package/dist/reducers/profileReducer.js +0 -136
  58. package/dist/services/OxyClient.d.ts +0 -84
  59. package/dist/services/OxyClient.js +0 -309
  60. package/dist/services/api.service.d.ts +0 -61
  61. package/dist/services/api.service.js +0 -289
  62. package/dist/services/auth.service.d.ts +0 -87
  63. package/dist/services/auth.service.js +0 -266
  64. package/dist/services/index.d.ts +0 -30
  65. package/dist/services/index.js +0 -88
  66. package/dist/services/payment.service.d.ts +0 -20
  67. package/dist/services/payment.service.js +0 -56
  68. package/dist/services/privacy.service.d.ts +0 -16
  69. package/dist/services/privacy.service.js +0 -69
  70. package/dist/services/profile.service.d.ts +0 -20
  71. package/dist/services/profile.service.js +0 -158
  72. package/dist/services/subscription.service.d.ts +0 -7
  73. package/dist/services/subscription.service.js +0 -46
  74. package/dist/services/user.service.d.ts +0 -25
  75. package/dist/services/user.service.js +0 -109
  76. package/dist/styles/colors.d.ts +0 -24
  77. package/dist/styles/colors.js +0 -31
  78. package/dist/styles/shared.d.ts +0 -168
  79. package/dist/styles/shared.js +0 -177
  80. package/dist/types/index.d.ts +0 -136
  81. package/dist/types/index.js +0 -7
  82. package/dist/utils/api.d.ts +0 -20
  83. package/dist/utils/api.js +0 -546
  84. package/dist/utils/authEvents.d.ts +0 -44
  85. package/dist/utils/authEvents.js +0 -73
  86. package/dist/utils/errorHandler.d.ts +0 -68
  87. package/dist/utils/errorHandler.js +0 -166
  88. package/dist/utils/index.d.ts +0 -12
  89. package/dist/utils/index.js +0 -41
  90. package/dist/utils/logger.d.ts +0 -100
  91. package/dist/utils/logger.js +0 -298
  92. package/dist/utils/socket.d.ts +0 -6
  93. package/dist/utils/socket.js +0 -179
  94. package/dist/utils/socketConfig.d.ts +0 -32
  95. package/dist/utils/socketConfig.js +0 -67
  96. package/dist/utils/storage.d.ts +0 -54
  97. package/dist/utils/storage.js +0 -253
  98. /package/dist/{components/AuthBottomSheet → shared}/types.js +0 -0
@@ -1,309 +0,0 @@
1
- "use strict";
2
- /**
3
- * OxyClient Service
4
- *
5
- * A client library for interacting with the OxyHQ platform APIs.
6
- * Provides methods for accessing files, user profiles, and managing sessions.
7
- */
8
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
- return new (P || (P = Promise))(function (resolve, reject) {
11
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
- step((generator = generator.apply(thisArg, _arguments || [])).next());
15
- });
16
- };
17
- var __importDefault = (this && this.__importDefault) || function (mod) {
18
- return (mod && mod.__esModule) ? mod : { "default": mod };
19
- };
20
- Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.oxyClient = exports.OxyClient = void 0;
22
- const api_service_1 = require("./api.service");
23
- const config_1 = require("../config");
24
- const storage_1 = require("../utils/storage");
25
- const constants_1 = require("../constants");
26
- const errorHandler_1 = __importDefault(require("../utils/errorHandler"));
27
- /**
28
- * Client library for OxyHQ platform services
29
- */
30
- class OxyClient {
31
- constructor(baseUrl) {
32
- this.profileCache = new Map();
33
- this.PROFILE_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
34
- this.pendingRequests = new Map();
35
- this.baseUrl = baseUrl || config_1.OXY_API_CONFIG.CLOUD_URL;
36
- }
37
- /**
38
- * Get metadata for multiple files by their IDs
39
- * @param mediaIds Array of file IDs
40
- * @returns Promise resolving to array of file metadata objects
41
- */
42
- getFilesData(mediaIds) {
43
- return __awaiter(this, void 0, void 0, function* () {
44
- if (!mediaIds || mediaIds.length === 0)
45
- return [];
46
- try {
47
- const validIds = mediaIds.filter(Boolean);
48
- if (validIds.length === 0)
49
- return [];
50
- const cacheKey = `files_data_${validIds.join(",")}`;
51
- // Return existing promise if request is already in progress
52
- if (this.pendingRequests.has(cacheKey)) {
53
- return this.pendingRequests.get(cacheKey);
54
- }
55
- // Create new request promise
56
- const requestPromise = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
57
- try {
58
- const response = yield api_service_1.apiService.get(`/files/data/${validIds.join(",")}`, {
59
- useCache: true,
60
- cacheTTL: 2 * 60 * 1000 // 2 minutes cache
61
- });
62
- resolve(Array.isArray(response.data) ? response.data : []);
63
- }
64
- catch (error) {
65
- errorHandler_1.default.handleError(error, {
66
- context: 'Error fetching files data',
67
- showToast: false
68
- });
69
- resolve([]); // Resolve with empty array instead of rejecting
70
- }
71
- finally {
72
- // Remove from pending requests
73
- this.pendingRequests.delete(cacheKey);
74
- }
75
- }));
76
- // Store the pending request
77
- this.pendingRequests.set(cacheKey, requestPromise);
78
- return requestPromise;
79
- }
80
- catch (error) {
81
- errorHandler_1.default.handleError(error, {
82
- context: 'Error in getFilesData',
83
- showToast: false
84
- });
85
- return [];
86
- }
87
- });
88
- }
89
- /**
90
- * Get the URL for accessing a file
91
- * @param fileId ID of the file
92
- * @returns Promise resolving to the file URL
93
- */
94
- getFileUrl(fileId) {
95
- return __awaiter(this, void 0, void 0, function* () {
96
- if (!fileId)
97
- throw new Error('File ID is required');
98
- return `${this.baseUrl}/${fileId}`;
99
- });
100
- }
101
- /**
102
- * Get a user profile by ID
103
- * @param userId ID of the user
104
- * @returns Promise resolving to the user profile
105
- */
106
- getProfile(userId) {
107
- return __awaiter(this, void 0, void 0, function* () {
108
- if (!userId)
109
- throw new Error('User ID is required');
110
- try {
111
- // Check cache first
112
- const cachedProfile = this.profileCache.get(userId);
113
- if (cachedProfile && (Date.now() - cachedProfile.timestamp) < this.PROFILE_CACHE_TTL) {
114
- return cachedProfile.profile;
115
- }
116
- const cacheKey = `profile_${userId}`;
117
- // Return existing promise if request is already in progress
118
- if (this.pendingRequests.has(cacheKey)) {
119
- return this.pendingRequests.get(cacheKey);
120
- }
121
- // Create new request promise
122
- const requestPromise = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
123
- try {
124
- const response = yield api_service_1.apiService.get(constants_1.ENDPOINTS.USERS.PROFILE(userId), { useCache: true });
125
- // Update cache
126
- this.profileCache.set(userId, {
127
- profile: response.data,
128
- timestamp: Date.now()
129
- });
130
- resolve(response.data);
131
- }
132
- catch (error) {
133
- errorHandler_1.default.handleError(error, {
134
- context: 'Error fetching profile',
135
- fallbackMessage: constants_1.ERROR_MESSAGES.DEFAULT
136
- });
137
- reject(new Error(constants_1.ERROR_MESSAGES.DEFAULT));
138
- }
139
- finally {
140
- // Remove from pending requests
141
- this.pendingRequests.delete(cacheKey);
142
- }
143
- }));
144
- // Store the pending request
145
- this.pendingRequests.set(cacheKey, requestPromise);
146
- return requestPromise;
147
- }
148
- catch (error) {
149
- errorHandler_1.default.handleError(error, {
150
- context: 'Error in getProfile',
151
- fallbackMessage: constants_1.ERROR_MESSAGES.DEFAULT
152
- });
153
- throw new Error(constants_1.ERROR_MESSAGES.DEFAULT);
154
- }
155
- });
156
- }
157
- /**
158
- * Get a user profile by username
159
- * @param username Username of the user
160
- * @returns Promise resolving to the user profile
161
- */
162
- getProfileByUsername(username) {
163
- return __awaiter(this, void 0, void 0, function* () {
164
- if (!username)
165
- throw new Error('Username is required');
166
- try {
167
- const cacheKey = `profile_username_${username}`;
168
- // Return existing promise if request is already in progress
169
- if (this.pendingRequests.has(cacheKey)) {
170
- return this.pendingRequests.get(cacheKey);
171
- }
172
- // Create new request promise
173
- const requestPromise = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
174
- try {
175
- const response = yield api_service_1.apiService.get(`/profiles/username/${username}`, { useCache: true });
176
- // Also cache by user ID for future lookups
177
- if (response.data.userID) {
178
- this.profileCache.set(response.data.userID, {
179
- profile: response.data,
180
- timestamp: Date.now()
181
- });
182
- }
183
- resolve(response.data);
184
- }
185
- catch (error) {
186
- errorHandler_1.default.handleError(error, {
187
- context: 'Error fetching profile by username',
188
- fallbackMessage: constants_1.ERROR_MESSAGES.DEFAULT
189
- });
190
- reject(new Error(constants_1.ERROR_MESSAGES.DEFAULT));
191
- }
192
- finally {
193
- // Remove from pending requests
194
- this.pendingRequests.delete(cacheKey);
195
- }
196
- }));
197
- // Store the pending request
198
- this.pendingRequests.set(cacheKey, requestPromise);
199
- return requestPromise;
200
- }
201
- catch (error) {
202
- errorHandler_1.default.handleError(error, {
203
- context: 'Error in getProfileByUsername',
204
- fallbackMessage: constants_1.ERROR_MESSAGES.DEFAULT
205
- });
206
- throw new Error(constants_1.ERROR_MESSAGES.DEFAULT);
207
- }
208
- });
209
- }
210
- /**
211
- * Get all user sessions
212
- * @returns Promise resolving to session data
213
- */
214
- getSessions() {
215
- return __awaiter(this, void 0, void 0, function* () {
216
- try {
217
- // Get the current user ID
218
- const userId = yield (0, storage_1.getData)(constants_1.STORAGE_KEYS.USER_ID);
219
- if (!userId) {
220
- console.warn('No user ID available when fetching sessions');
221
- // Return empty sessions if there's no user ID
222
- return { sessions: [] };
223
- }
224
- // First try to get from API with the user ID as a query parameter
225
- const response = yield api_service_1.apiService.get(constants_1.ENDPOINTS.USERS.SESSIONS, {
226
- useCache: true,
227
- params: { userId } // Include userId as a parameter
228
- });
229
- // Store the sessions locally for offline access
230
- yield (0, storage_1.storeData)(constants_1.STORAGE_KEYS.SESSIONS, response.data.sessions);
231
- return response.data;
232
- }
233
- catch (error) {
234
- errorHandler_1.default.handleError(error, {
235
- context: 'Error fetching sessions',
236
- showToast: false
237
- });
238
- // Fallback to locally stored sessions
239
- const localSessions = yield (0, storage_1.getData)(constants_1.STORAGE_KEYS.SESSIONS);
240
- if (localSessions) {
241
- return { sessions: localSessions };
242
- }
243
- return { sessions: [] }; // Return empty sessions array if nothing found
244
- }
245
- });
246
- }
247
- /**
248
- * Switch to a different user session
249
- * @param userId ID of the user to switch to
250
- * @returns Promise resolving to session switch response
251
- */
252
- switchSession(userId) {
253
- return __awaiter(this, void 0, void 0, function* () {
254
- if (!userId)
255
- throw new Error('User ID is required');
256
- try {
257
- const response = yield api_service_1.apiService.post('/auth/switch-session', { userId });
258
- return response.data;
259
- }
260
- catch (error) {
261
- errorHandler_1.default.handleError(error, {
262
- context: 'Error switching session',
263
- fallbackMessage: constants_1.ERROR_MESSAGES.DEFAULT
264
- });
265
- throw new Error(constants_1.ERROR_MESSAGES.DEFAULT);
266
- }
267
- });
268
- }
269
- /**
270
- * Get recommended profiles to follow
271
- * @param limit Optional number of recommendations to return
272
- * @returns Promise resolving to array of recommended profiles
273
- */
274
- getRecommendations(limit) {
275
- return __awaiter(this, void 0, void 0, function* () {
276
- try {
277
- const params = limit ? { limit: limit.toString() } : undefined;
278
- const response = yield api_service_1.apiService.get('/profiles/recommendations', {
279
- params,
280
- useCache: true,
281
- cacheTTL: 15 * 60 * 1000 // 15 minutes cache for recommendations
282
- });
283
- return response.data;
284
- }
285
- catch (error) {
286
- errorHandler_1.default.handleError(error, {
287
- context: 'Error fetching recommendations',
288
- showToast: false
289
- });
290
- return []; // Return empty array instead of throwing
291
- }
292
- });
293
- }
294
- /**
295
- * Clear profile cache
296
- * @param userId Optional user ID to clear specific cache entry
297
- */
298
- clearProfileCache(userId) {
299
- if (userId) {
300
- this.profileCache.delete(userId);
301
- }
302
- else {
303
- this.profileCache.clear();
304
- }
305
- }
306
- }
307
- exports.OxyClient = OxyClient;
308
- // Export singleton instance
309
- exports.oxyClient = new OxyClient();
@@ -1,61 +0,0 @@
1
- import { AxiosResponse } from 'axios';
2
- declare class ApiService {
3
- private api;
4
- private isRefreshing;
5
- private failedQueue;
6
- private cache;
7
- private abortControllers;
8
- constructor();
9
- private setupInterceptors;
10
- private processQueue;
11
- private getRequestId;
12
- private getCacheKey;
13
- private isCacheValid;
14
- /**
15
- * Cancel all pending requests
16
- */
17
- cancelAllRequests(): void;
18
- /**
19
- * Cancel a specific request
20
- */
21
- cancelRequest(requestId: string): void;
22
- /**
23
- * Clear the entire cache
24
- */
25
- clearCache(): void;
26
- /**
27
- * Clear a specific cache entry
28
- */
29
- clearCacheEntry(url: string, params?: any): void;
30
- /**
31
- * Make a GET request with optional caching
32
- */
33
- get<T>(url: string, config?: {
34
- params?: any;
35
- useCache?: boolean;
36
- cacheTTL?: number;
37
- headers?: any;
38
- }): Promise<AxiosResponse<T>>;
39
- /**
40
- * Make a POST request
41
- */
42
- post<T>(url: string, data?: any, config?: any): Promise<AxiosResponse<T>>;
43
- /**
44
- * Make a PUT request
45
- */
46
- put<T>(url: string, data?: any, config?: any): Promise<AxiosResponse<T>>;
47
- /**
48
- * Make a DELETE request
49
- */
50
- delete<T>(url: string, config?: any): Promise<AxiosResponse<T>>;
51
- /**
52
- * Make a PATCH request
53
- */
54
- patch<T>(url: string, data?: any, config?: any): Promise<AxiosResponse<T>>;
55
- /**
56
- * Handle common request errors
57
- */
58
- private handleRequestError;
59
- }
60
- export declare const apiService: ApiService;
61
- export {};
@@ -1,289 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.apiService = void 0;
16
- const axios_1 = __importDefault(require("axios"));
17
- const storage_1 = require("../utils/storage");
18
- const config_1 = require("../config");
19
- const constants_1 = require("../constants");
20
- // Import authEvents instead of showAuthBottomSheet
21
- const authEvents_1 = require("../utils/authEvents");
22
- class ApiService {
23
- constructor() {
24
- this.isRefreshing = false;
25
- this.failedQueue = [];
26
- this.cache = new Map();
27
- this.abortControllers = new Map();
28
- this.api = axios_1.default.create({
29
- baseURL: config_1.OXY_API_CONFIG.BASE_URL,
30
- timeout: config_1.OXY_API_CONFIG.TIMEOUT,
31
- headers: {
32
- 'Content-Type': 'application/json'
33
- }
34
- });
35
- this.setupInterceptors();
36
- }
37
- setupInterceptors() {
38
- this.api.interceptors.request.use((config) => __awaiter(this, void 0, void 0, function* () {
39
- try {
40
- const accessToken = yield (0, storage_1.getSecureData)('accessToken');
41
- if (accessToken && config.headers) {
42
- config.headers.Authorization = `Bearer ${accessToken}`;
43
- }
44
- // Add abort controller to each request
45
- if (config.method && ['get', 'post', 'put', 'delete', 'patch'].includes(config.method)) {
46
- const controller = new AbortController();
47
- const requestId = this.getRequestId(config);
48
- this.abortControllers.set(requestId, controller);
49
- config.signal = controller.signal;
50
- }
51
- return config;
52
- }
53
- catch (error) {
54
- console.error('Error in request interceptor:', error);
55
- return config;
56
- }
57
- }));
58
- this.api.interceptors.response.use((response) => response, (error) => __awaiter(this, void 0, void 0, function* () {
59
- var _a;
60
- const originalRequest = error.config;
61
- // Clean up abort controller after request completes
62
- if (originalRequest) {
63
- const requestId = this.getRequestId(originalRequest);
64
- this.abortControllers.delete(requestId);
65
- }
66
- if (!originalRequest || ((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) !== 401 || originalRequest._retry) {
67
- return Promise.reject(error);
68
- }
69
- if (this.isRefreshing) {
70
- return new Promise((resolve, reject) => {
71
- this.failedQueue.push({ resolve, reject, config: originalRequest });
72
- });
73
- }
74
- originalRequest._retry = true;
75
- this.isRefreshing = true;
76
- try {
77
- const refreshToken = yield (0, storage_1.getSecureData)('refreshToken');
78
- if (!refreshToken) {
79
- throw new Error('No refresh token available');
80
- }
81
- const response = yield axios_1.default.post(`${config_1.OXY_API_CONFIG.BASE_URL}/auth/refresh`, { refreshToken });
82
- const { accessToken, refreshToken: newRefreshToken } = response.data;
83
- if (!accessToken) {
84
- throw new Error('Invalid refresh response');
85
- }
86
- // Store new tokens
87
- yield Promise.all([
88
- (0, storage_1.storeSecureData)('accessToken', accessToken),
89
- newRefreshToken ? (0, storage_1.storeSecureData)('refreshToken', newRefreshToken) : Promise.resolve()
90
- ]);
91
- // Update authorization header
92
- this.api.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
93
- if (originalRequest.headers) {
94
- originalRequest.headers['Authorization'] = `Bearer ${accessToken}`;
95
- }
96
- // Process queued requests
97
- this.processQueue(null, accessToken);
98
- // Retry original request
99
- return this.api(originalRequest);
100
- }
101
- catch (refreshError) {
102
- // Process queued requests with error
103
- this.processQueue(refreshError);
104
- // Clear tokens and show auth screen
105
- yield Promise.all([
106
- (0, storage_1.storeSecureData)('accessToken', null),
107
- (0, storage_1.storeSecureData)('refreshToken', null)
108
- ]);
109
- // Use authEvents instead of direct function call
110
- authEvents_1.authEvents.requireAuth();
111
- return Promise.reject(refreshError);
112
- }
113
- finally {
114
- this.isRefreshing = false;
115
- }
116
- }));
117
- }
118
- processQueue(error, accessToken) {
119
- this.failedQueue.forEach(({ resolve, reject, config }) => {
120
- if (error) {
121
- reject(error);
122
- }
123
- else if (accessToken && config.headers) {
124
- config.headers['Authorization'] = `Bearer ${accessToken}`;
125
- resolve(this.api(config));
126
- }
127
- });
128
- this.failedQueue = [];
129
- }
130
- getRequestId(config) {
131
- const { method, url, params, data } = config;
132
- return `${method}:${url}:${JSON.stringify(params || {})}:${JSON.stringify(data || {})}`;
133
- }
134
- getCacheKey(url, params) {
135
- return `${url}:${JSON.stringify(params || {})}`;
136
- }
137
- isCacheValid(cacheItem) {
138
- return Date.now() < cacheItem.expiresAt;
139
- }
140
- /**
141
- * Cancel all pending requests
142
- */
143
- cancelAllRequests() {
144
- this.abortControllers.forEach(controller => {
145
- controller.abort();
146
- });
147
- this.abortControllers.clear();
148
- }
149
- /**
150
- * Cancel a specific request
151
- */
152
- cancelRequest(requestId) {
153
- const controller = this.abortControllers.get(requestId);
154
- if (controller) {
155
- controller.abort();
156
- this.abortControllers.delete(requestId);
157
- }
158
- }
159
- /**
160
- * Clear the entire cache
161
- */
162
- clearCache() {
163
- this.cache.clear();
164
- }
165
- /**
166
- * Clear a specific cache entry
167
- */
168
- clearCacheEntry(url, params) {
169
- const cacheKey = this.getCacheKey(url, params);
170
- this.cache.delete(cacheKey);
171
- }
172
- /**
173
- * Make a GET request with optional caching
174
- */
175
- get(url, config) {
176
- return __awaiter(this, void 0, void 0, function* () {
177
- const { params, useCache = false, cacheTTL = config_1.OXY_CACHE_CONFIG.DEFAULT_TTL } = config || {};
178
- if (useCache) {
179
- const cacheKey = this.getCacheKey(url, params);
180
- const cachedItem = this.cache.get(cacheKey);
181
- if (cachedItem && this.isCacheValid(cachedItem)) {
182
- return {
183
- data: cachedItem.data,
184
- status: 200,
185
- statusText: 'OK (cached)',
186
- headers: {},
187
- config: {}
188
- };
189
- }
190
- }
191
- try {
192
- const response = yield this.api.get(url, Object.assign({}, config));
193
- if (useCache) {
194
- const cacheKey = this.getCacheKey(url, params);
195
- this.cache.set(cacheKey, {
196
- data: response.data,
197
- timestamp: Date.now(),
198
- expiresAt: Date.now() + cacheTTL
199
- });
200
- }
201
- return response;
202
- }
203
- catch (error) {
204
- this.handleRequestError(error);
205
- throw error;
206
- }
207
- });
208
- }
209
- /**
210
- * Make a POST request
211
- */
212
- post(url, data, config) {
213
- return __awaiter(this, void 0, void 0, function* () {
214
- try {
215
- return yield this.api.post(url, data, config);
216
- }
217
- catch (error) {
218
- this.handleRequestError(error);
219
- throw error;
220
- }
221
- });
222
- }
223
- /**
224
- * Make a PUT request
225
- */
226
- put(url, data, config) {
227
- return __awaiter(this, void 0, void 0, function* () {
228
- try {
229
- return yield this.api.put(url, data, config);
230
- }
231
- catch (error) {
232
- this.handleRequestError(error);
233
- throw error;
234
- }
235
- });
236
- }
237
- /**
238
- * Make a DELETE request
239
- */
240
- delete(url, config) {
241
- return __awaiter(this, void 0, void 0, function* () {
242
- try {
243
- return yield this.api.delete(url, config);
244
- }
245
- catch (error) {
246
- this.handleRequestError(error);
247
- throw error;
248
- }
249
- });
250
- }
251
- /**
252
- * Make a PATCH request
253
- */
254
- patch(url, data, config) {
255
- return __awaiter(this, void 0, void 0, function* () {
256
- try {
257
- return yield this.api.patch(url, data, config);
258
- }
259
- catch (error) {
260
- this.handleRequestError(error);
261
- throw error;
262
- }
263
- });
264
- }
265
- /**
266
- * Handle common request errors
267
- */
268
- handleRequestError(error) {
269
- if (axios_1.default.isAxiosError(error)) {
270
- const axiosError = error;
271
- if (axiosError.code === 'ECONNABORTED') {
272
- console.error('Request timeout:', axiosError.message);
273
- }
274
- else if (axiosError.response) {
275
- console.error(`API Error ${axiosError.response.status}:`, axiosError.response.data || constants_1.ERROR_MESSAGES.DEFAULT);
276
- }
277
- else if (axiosError.request) {
278
- console.error('No response received:', axiosError.message);
279
- }
280
- else {
281
- console.error('Request error:', axiosError.message);
282
- }
283
- }
284
- else {
285
- console.error('Unexpected error:', error);
286
- }
287
- }
288
- }
289
- exports.apiService = new ApiService();