@dashadmin/dash-axios-hook 1.0.0

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 (4) hide show
  1. package/README.md +380 -0
  2. package/index.d.ts +3 -0
  3. package/index.js +154 -0
  4. package/package.json +32 -0
package/README.md ADDED
@@ -0,0 +1,380 @@
1
+ # dash-axios-hook
2
+
3
+ A React hook package for making HTTP requests with axios in the DASH framework. This hook provides automatic API prefix handling and is designed to work seamlessly with DASH's authentication system.
4
+
5
+ ## Installation
6
+
7
+ This package is part of the DASH monorepo and is installed automatically when you install the workspace dependencies.
8
+
9
+ ```bash
10
+ pnpm install
11
+ ```
12
+
13
+ ## Features
14
+
15
+ - 🔐 **Automatic authentication** - Integrates with DASH auth system
16
+ - 🔄 **API prefix handling** - Automatically appends `/api` to all requests
17
+ - 📦 **TypeScript support** - Full type definitions included
18
+ - ⚡ **React hook interface** - Easy to use in functional components
19
+
20
+ ## Basic Usage
21
+
22
+ ### Simple GET Request
23
+
24
+ ```tsx
25
+ import { useAxios } from 'dash-axios-hook';
26
+
27
+ function MyComponent() {
28
+ const { axios } = useAxios();
29
+ const [data, setData] = useState(null);
30
+
31
+ useEffect(() => {
32
+ const fetchData = async () => {
33
+ // axios automatically appends "/api" prefix
34
+ // This calls: /api/tenancy/users
35
+ const response = await axios.get('tenancy/users');
36
+ setData(response.data);
37
+ };
38
+
39
+ fetchData();
40
+ }, [axios]);
41
+
42
+ return <div>{JSON.stringify(data)}</div>;
43
+ }
44
+ ```
45
+
46
+ ### POST Request with Data
47
+
48
+ ```tsx
49
+ import { useAxios } from 'dash-axios-hook';
50
+
51
+ function CreateUserForm() {
52
+ const { axios } = useAxios();
53
+
54
+ const handleSubmit = async (formData) => {
55
+ try {
56
+ // This calls: /api/tenancy/users
57
+ const response = await axios.post('tenancy/users', {
58
+ name: formData.name,
59
+ email: formData.email,
60
+ });
61
+
62
+ console.log('User created:', response.data);
63
+ } catch (error) {
64
+ console.error('Error creating user:', error);
65
+ }
66
+ };
67
+
68
+ return <form onSubmit={handleSubmit}>...</form>;
69
+ }
70
+ ```
71
+
72
+ ### PUT/PATCH Request
73
+
74
+ ```tsx
75
+ import { useAxios } from 'dash-axios-hook';
76
+
77
+ function UpdateUserForm({ userId }) {
78
+ const { axios } = useAxios();
79
+
80
+ const handleUpdate = async (formData) => {
81
+ // This calls: /api/tenancy/users/123
82
+ await axios.put(`tenancy/users/${userId}`, formData);
83
+ };
84
+
85
+ return <form onSubmit={handleUpdate}>...</form>;
86
+ }
87
+ ```
88
+
89
+ ### DELETE Request
90
+
91
+ ```tsx
92
+ import { useAxios } from 'dash-axios-hook';
93
+
94
+ function DeleteUserButton({ userId }) {
95
+ const { axios } = useAxios();
96
+
97
+ const handleDelete = async () => {
98
+ // This calls: /api/tenancy/users/123
99
+ await axios.delete(`tenancy/users/${userId}`);
100
+ };
101
+
102
+ return <button onClick={handleDelete}>Delete</button>;
103
+ }
104
+ ```
105
+
106
+ ## Advanced Usage
107
+
108
+ ### Custom Hook for Specific Resource
109
+
110
+ Create reusable hooks for specific API endpoints:
111
+
112
+ ```tsx
113
+ import { useState, useEffect } from 'react';
114
+ import { useAxios } from 'dash-axios-hook';
115
+
116
+ export interface PaymentGatewayCapabilities {
117
+ billing_cycles: string[];
118
+ supports_subscriptions: boolean;
119
+ supports_trials: boolean;
120
+ }
121
+
122
+ export interface PaymentGatewayCapabilitiesResponse {
123
+ gateway: string;
124
+ gateway_name: string;
125
+ capabilities: PaymentGatewayCapabilities;
126
+ }
127
+
128
+ /**
129
+ * Hook to fetch payment gateway capabilities for the current tenancy
130
+ */
131
+ export const usePaymentGatewayCapabilities = () => {
132
+ const { axios } = useAxios();
133
+ const [data, setData] = useState<PaymentGatewayCapabilitiesResponse | null>(null);
134
+ const [isLoading, setIsLoading] = useState(true);
135
+ const [error, setError] = useState<Error | null>(null);
136
+
137
+ useEffect(() => {
138
+ const fetchCapabilities = async () => {
139
+ try {
140
+ setIsLoading(true);
141
+ setError(null);
142
+
143
+ // axios automatically appends "/api" prefix
144
+ // This calls: /api/tenancy/payment-gateway/capabilities
145
+ const response = await axios.get<PaymentGatewayCapabilitiesResponse>(
146
+ 'tenancy/payment-gateway/capabilities'
147
+ );
148
+
149
+ setData(response.data);
150
+ } catch (err) {
151
+ console.error('Error fetching payment gateway capabilities:', err);
152
+ setError(err as Error);
153
+
154
+ // Set fallback data on error
155
+ setData({
156
+ gateway: 'unknown',
157
+ gateway_name: 'Unknown Gateway',
158
+ capabilities: {
159
+ billing_cycles: ['monthly'],
160
+ supports_subscriptions: false,
161
+ supports_trials: false,
162
+ }
163
+ });
164
+ } finally {
165
+ setIsLoading(false);
166
+ }
167
+ };
168
+
169
+ fetchCapabilities();
170
+ }, [axios]);
171
+
172
+ return {
173
+ data,
174
+ gateway: data?.gateway ?? null,
175
+ gatewayName: data?.gateway_name ?? null,
176
+ capabilities: data?.capabilities ?? {
177
+ billing_cycles: ['monthly'],
178
+ supports_subscriptions: false,
179
+ supports_trials: false,
180
+ },
181
+ supportedBillingCycles: data?.capabilities?.billing_cycles ?? ['monthly'],
182
+ isLoading,
183
+ error,
184
+ };
185
+ };
186
+
187
+ // Usage in component:
188
+ function SubscriptionPlans() {
189
+ const { supportedBillingCycles, isLoading } = usePaymentGatewayCapabilities();
190
+
191
+ if (isLoading) return <CircularProgress />;
192
+
193
+ // Filter plans based on gateway capabilities
194
+ const filteredPlans = plans.filter(plan =>
195
+ supportedBillingCycles.includes(plan.billing_cycle)
196
+ );
197
+
198
+ return <PlansList plans={filteredPlans} />;
199
+ }
200
+ ```
201
+
202
+ ### With Loading States and Error Handling
203
+
204
+ ```tsx
205
+ import { useState, useEffect } from 'react';
206
+ import { useAxios } from 'dash-axios-hook';
207
+
208
+ function UsersList() {
209
+ const { axios } = useAxios();
210
+ const [users, setUsers] = useState([]);
211
+ const [loading, setLoading] = useState(true);
212
+ const [error, setError] = useState(null);
213
+
214
+ useEffect(() => {
215
+ const fetchUsers = async () => {
216
+ try {
217
+ setLoading(true);
218
+ setError(null);
219
+
220
+ const response = await axios.get('tenancy/users');
221
+ setUsers(response.data);
222
+ } catch (err) {
223
+ setError(err.message);
224
+ } finally {
225
+ setLoading(false);
226
+ }
227
+ };
228
+
229
+ fetchUsers();
230
+ }, [axios]);
231
+
232
+ if (loading) return <div>Loading...</div>;
233
+ if (error) return <div>Error: {error}</div>;
234
+
235
+ return (
236
+ <ul>
237
+ {users.map(user => (
238
+ <li key={user.id}>{user.name}</li>
239
+ ))}
240
+ </ul>
241
+ );
242
+ }
243
+ ```
244
+
245
+ ### Query Parameters
246
+
247
+ ```tsx
248
+ import { useAxios } from 'dash-axios-hook';
249
+
250
+ function FilteredUsers() {
251
+ const { axios } = useAxios();
252
+
253
+ const fetchUsers = async (filters) => {
254
+ // This calls: /api/tenancy/users?role=admin&status=active
255
+ const response = await axios.get('tenancy/users', {
256
+ params: {
257
+ role: filters.role,
258
+ status: filters.status,
259
+ }
260
+ });
261
+
262
+ return response.data;
263
+ };
264
+
265
+ return <div>...</div>;
266
+ }
267
+ ```
268
+
269
+ ### File Upload
270
+
271
+ ```tsx
272
+ import { useAxios } from 'dash-axios-hook';
273
+
274
+ function FileUpload() {
275
+ const { axios } = useAxios();
276
+
277
+ const handleFileUpload = async (file) => {
278
+ const formData = new FormData();
279
+ formData.append('file', file);
280
+ formData.append('name', 'My Document');
281
+
282
+ // This calls: /api/tenancy/documents
283
+ const response = await axios.post('tenancy/documents', formData, {
284
+ headers: {
285
+ 'Content-Type': 'multipart/form-data',
286
+ },
287
+ });
288
+
289
+ return response.data;
290
+ };
291
+
292
+ return <input type="file" onChange={(e) => handleFileUpload(e.target.files[0])} />;
293
+ }
294
+ ```
295
+
296
+ ## Important Notes
297
+
298
+ ### Automatic `/api` Prefix
299
+
300
+ The `useAxios` hook **automatically prepends `/api`** to all requests. Do not include `/api` in your URLs:
301
+
302
+ ```tsx
303
+ // ✅ Correct
304
+ await axios.get('tenancy/users'); // Calls: /api/tenancy/users
305
+
306
+ // ❌ Incorrect
307
+ await axios.get('/api/tenancy/users'); // Calls: /api/api/tenancy/users
308
+ ```
309
+
310
+ ### Authentication
311
+
312
+ The hook automatically includes authentication tokens from the DASH auth system. No additional configuration is needed.
313
+
314
+ ### Error Handling
315
+
316
+ Always wrap axios calls in try-catch blocks:
317
+
318
+ ```tsx
319
+ try {
320
+ const response = await axios.get('tenancy/users');
321
+ // Handle success
322
+ } catch (error) {
323
+ // Handle error
324
+ if (error.response) {
325
+ // Server responded with error status
326
+ console.error('Server error:', error.response.data);
327
+ } else if (error.request) {
328
+ // Request made but no response
329
+ console.error('Network error');
330
+ } else {
331
+ // Error setting up request
332
+ console.error('Request error:', error.message);
333
+ }
334
+ }
335
+ ```
336
+
337
+ ## TypeScript Support
338
+
339
+ The hook supports TypeScript generics for type-safe responses:
340
+
341
+ ```tsx
342
+ interface User {
343
+ id: number;
344
+ name: string;
345
+ email: string;
346
+ }
347
+
348
+ const { axios } = useAxios();
349
+
350
+ // Type-safe response
351
+ const response = await axios.get<User[]>('tenancy/users');
352
+ // response.data is now typed as User[]
353
+ ```
354
+
355
+ ## API Reference
356
+
357
+ ### `useAxios()`
358
+
359
+ Returns an object with an axios instance configured for the DASH API.
360
+
361
+ **Returns:**
362
+ - `axios`: Configured axios instance with automatic `/api` prefix
363
+
364
+ **Example:**
365
+ ```tsx
366
+ const { axios } = useAxios();
367
+ ```
368
+
369
+ ## Best Practices
370
+
371
+ 1. **Always use the hook at component level**, not in utility functions
372
+ 2. **Include error handling** for all requests
373
+ 3. **Use loading states** for better UX
374
+ 4. **Don't include `/api`** in your URLs - it's added automatically
375
+ 5. **Create custom hooks** for reusable API logic
376
+ 6. **Use TypeScript generics** for type safety
377
+
378
+ ## Contributing
379
+
380
+ This package is part of the DASH monorepo. See the main repository README for contribution guidelines.
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ // Auto-generated permissive types for @dashadmin/dash-axios-hook.
2
+ // Full typings can be regenerated with a tolerant tsc emit.
3
+ export {};
package/index.js ADDED
@@ -0,0 +1,154 @@
1
+ import k from "axios";
2
+ import { DASHAdminSystemConstants as A } from "@dashadmin/dash-constants";
3
+ import { dashStorage as l } from "@dashadmin/dash-utils";
4
+ import { useState as y, useEffect as v } from "react";
5
+ import { useStore as I } from "react-admin";
6
+ const _ = (t, n, a = "update") => {
7
+ n || (n = "");
8
+ const s = {
9
+ update: "Actualizar",
10
+ create: "Crear",
11
+ delete: "Eliminar"
12
+ }, e = t.response?.data?.message || t.message || "Error al " + (s[a] || a) + " el recurso", r = t.response?.status || 500;
13
+ let i = {
14
+ errors: {}
15
+ };
16
+ if (t.response?.data?.errors) {
17
+ const c = t.response.data.errors;
18
+ Object.keys(c).forEach((u) => {
19
+ typeof c[u] == "string" ? i.errors[u] = c[u] : Array.isArray(c[u]) ? i.errors[u] = c[u].join(", ") : typeof c[u] == "object" && (i.errors[u] = c[u]);
20
+ }), e && (i.errors.root = {
21
+ serverError: e
22
+ });
23
+ }
24
+ const o = {
25
+ message: e,
26
+ status: r,
27
+ body: i,
28
+ resource: n,
29
+ originalError: t,
30
+ name: "Error"
31
+ };
32
+ return console.error("Update error:", {
33
+ resource: n,
34
+ errorMessage: e,
35
+ status: r,
36
+ validationErrors: i.errors,
37
+ originalError: t
38
+ }), o;
39
+ };
40
+ let d = !1, g = [];
41
+ const p = (t, n = null) => {
42
+ g.forEach((a) => {
43
+ t ? a.reject(t) : a.resolve(n);
44
+ }), g = [];
45
+ }, j = async (t) => {
46
+ const n = l.getItem("refreshToken");
47
+ if (!n)
48
+ return console.log("[Axios] No refresh token available"), null;
49
+ try {
50
+ console.log("[Axios] Attempting to refresh access token...");
51
+ const s = await k.create({
52
+ baseURL: A.system.ADMIN_API_URL,
53
+ headers: {
54
+ "Content-Type": "application/json",
55
+ Accept: "application/json"
56
+ }
57
+ }).post("/auth/refresh", {
58
+ refresh_token: n
59
+ });
60
+ if (s.status === 200 && s.data.token) {
61
+ const e = s.data.token, r = s.data.refresh_token;
62
+ return l.setItem("token", e), r && l.setItem("refreshToken", r), console.log("[Axios] Token refresh successful"), e;
63
+ }
64
+ return null;
65
+ } catch (a) {
66
+ return console.error("[Axios] Token refresh failed:", a), null;
67
+ }
68
+ }, E = () => {
69
+ console.log("[Axios] Logging out due to authentication failure");
70
+ debugger;
71
+ l.clear(), localStorage.clear(), window.dispatchEvent(new CustomEvent("auth:logout", {
72
+ detail: { reason: "token_refresh_failed" }
73
+ }));
74
+ }, x = (t, n) => {
75
+ typeof navigator < "u" && navigator.language && navigator.language.split("-")[0];
76
+ const a = {
77
+ headers: {
78
+ "Content-Type": "application/json",
79
+ //'Accept-Language': browserLanguage || 'es', // fallback to 'es' if not available
80
+ "Accept-Language": "es",
81
+ Accept: "application/json"
82
+ },
83
+ ...t
84
+ }, s = k.create(a);
85
+ return s.interceptors.request.use(function(e) {
86
+ const r = l.getItem("token");
87
+ r !== void 0 && r !== "undefined" && (e.headers.Authorization = "Bearer " + r);
88
+ const i = l.getItem("active_tenant_id");
89
+ return i && (e.headers["X-Tenant-Id"] = i), e;
90
+ }), s.interceptors.response.use(
91
+ (e) => e,
92
+ async (e) => {
93
+ const r = e.config;
94
+ if (e.response?.status === 401 && !r._retry) {
95
+ if (r.url?.includes("/login") || r.url?.includes("/auth/refresh") || r.url?.includes("/logout"))
96
+ return Promise.reject(e);
97
+ if (d)
98
+ return new Promise((o, c) => {
99
+ g.push({ resolve: o, reject: c });
100
+ }).then((o) => (o && r.headers && (r.headers.Authorization = `Bearer ${o}`), s(r))).catch((o) => Promise.reject(o));
101
+ r._retry = !0, d = !0;
102
+ try {
103
+ const o = await j(s);
104
+ return o ? (r.headers && (r.headers.Authorization = `Bearer ${o}`), p(null, o), s(r)) : (p(e, null), E(), Promise.reject(e));
105
+ } catch (o) {
106
+ return p(o, null), E(), Promise.reject(o);
107
+ } finally {
108
+ d = !1;
109
+ }
110
+ }
111
+ return window.dispatchEvent(
112
+ new MessageEvent("DASHGlobalError", {
113
+ data: _(e, null, "list"),
114
+ origin: "AxiosInterceptor"
115
+ })
116
+ ), Promise.reject(e);
117
+ }
118
+ ), s;
119
+ }, w = (t) => x({
120
+ baseURL: A.system.ADMIN_API_URL,
121
+ ...t && { ...t }
122
+ }), U = (t) => x({
123
+ baseURL: A.system.ADMIN_API_URL,
124
+ ...t && { ...t }
125
+ }), T = (t, n, a) => n.split(".").reduce((s, e) => s ? s[e] : a, t), C = (t) => {
126
+ const {
127
+ /*method = 'GET',
128
+ url,
129
+ payload = null,*/
130
+ storeKey: n,
131
+ dataPath: a = "data"
132
+ } = t, s = w(), [e, r] = y(null), [i, o] = y(!1), [c, u] = I(n, null), m = async (h) => {
133
+ try {
134
+ const f = await s({
135
+ method: h.method,
136
+ url: `${h.url}${h.payload ? "?" + h.payload : ""}`
137
+ });
138
+ (f.status >= 200 || f.status < 300) && u(T(f, a, null));
139
+ } catch (f) {
140
+ r(f);
141
+ } finally {
142
+ o(!0);
143
+ }
144
+ };
145
+ return v(() => {
146
+ c || m(t);
147
+ }, []), { request: m, results: c, error: e, loaded: i };
148
+ };
149
+ export {
150
+ U as createAxiosInstance,
151
+ _ as processAxiosError,
152
+ w as useAxios,
153
+ C as useAxiosGetWithStore
154
+ };
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@dashadmin/dash-axios-hook",
3
+ "version": "1.0.0",
4
+ "description": "dash-axios-hook — DASH framework package",
5
+ "license": "MIT",
6
+ "author": "Francisco Aranda <farandal@gmail.com>",
7
+ "type": "module",
8
+ "main": "index.js",
9
+ "module": "index.js",
10
+ "types": "index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./index.d.ts",
14
+ "import": "./index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "**/*"
19
+ ],
20
+ "sideEffects": false,
21
+ "dependencies": {
22
+ "@mui/material": "^7.3.10",
23
+ "@dashadmin/dash-constants": "^1.0.0",
24
+ "@dashadmin/dash-utils": "^1.0.0"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "engines": {
30
+ "node": ">=18"
31
+ }
32
+ }