@forgepack/request 1.0.4

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 (87) hide show
  1. package/LICENCE +21 -0
  2. package/README.md +164 -0
  3. package/dist/api/api.d.ts +8 -0
  4. package/dist/api/api.d.ts.map +1 -0
  5. package/dist/api/api.js +35 -0
  6. package/dist/api/client.d.ts +30 -0
  7. package/dist/api/client.d.ts.map +1 -0
  8. package/dist/api/client.js +50 -0
  9. package/dist/component/auth.d.ts +8 -0
  10. package/dist/component/auth.d.ts.map +1 -0
  11. package/dist/component/auth.js +9 -0
  12. package/dist/component/errorMessage.d.ts +6 -0
  13. package/dist/component/errorMessage.d.ts.map +1 -0
  14. package/dist/component/errorMessage.js +7 -0
  15. package/dist/component/request.d.ts +13 -0
  16. package/dist/component/request.d.ts.map +1 -0
  17. package/dist/component/request.js +12 -0
  18. package/dist/component/response.d.ts +13 -0
  19. package/dist/component/response.d.ts.map +1 -0
  20. package/dist/component/response.js +13 -0
  21. package/dist/component/token.d.ts +32 -0
  22. package/dist/component/token.d.ts.map +1 -0
  23. package/dist/component/token.js +16 -0
  24. package/dist/hook/useProvider.d.ts +13 -0
  25. package/dist/hook/useProvider.d.ts.map +1 -0
  26. package/dist/hook/useProvider.js +51 -0
  27. package/dist/hook/useRequest.d.ts +11 -0
  28. package/dist/hook/useRequest.d.ts.map +1 -0
  29. package/dist/hook/useRequest.js +38 -0
  30. package/dist/hook/useRequireAuth.d.ts +4 -0
  31. package/dist/hook/useRequireAuth.d.ts.map +1 -0
  32. package/dist/hook/useRequireAuth.js +21 -0
  33. package/dist/hooks/AuthContext.d.ts +19 -0
  34. package/dist/hooks/AuthContext.d.ts.map +1 -0
  35. package/dist/hooks/AuthContext.js +10 -0
  36. package/dist/hooks/AuthProvider.d.ts +27 -0
  37. package/dist/hooks/AuthProvider.d.ts.map +1 -0
  38. package/dist/hooks/AuthProvider.js +71 -0
  39. package/dist/hooks/useAuth.d.ts +33 -0
  40. package/dist/hooks/useAuth.d.ts.map +1 -0
  41. package/dist/hooks/useAuth.js +50 -0
  42. package/dist/hooks/useRequest.d.ts +37 -0
  43. package/dist/hooks/useRequest.d.ts.map +1 -0
  44. package/dist/hooks/useRequest.js +63 -0
  45. package/dist/index.d.ts +29 -0
  46. package/dist/index.d.ts.map +1 -0
  47. package/dist/index.js +49 -0
  48. package/dist/service/crud.d.ts +15 -0
  49. package/dist/service/crud.d.ts.map +1 -0
  50. package/dist/service/crud.js +116 -0
  51. package/dist/service/fetchPage.d.ts +5 -0
  52. package/dist/service/fetchPage.d.ts.map +1 -0
  53. package/dist/service/fetchPage.js +22 -0
  54. package/dist/service/token.d.ts +10 -0
  55. package/dist/service/token.d.ts.map +1 -0
  56. package/dist/service/token.js +93 -0
  57. package/dist/services/api.d.ts +33 -0
  58. package/dist/services/api.d.ts.map +1 -0
  59. package/dist/services/api.js +50 -0
  60. package/dist/services/auth.d.ts +51 -0
  61. package/dist/services/auth.d.ts.map +1 -0
  62. package/dist/services/auth.js +117 -0
  63. package/dist/services/crud.d.ts +120 -0
  64. package/dist/services/crud.d.ts.map +1 -0
  65. package/dist/services/crud.js +199 -0
  66. package/dist/services/token.d.ts +88 -0
  67. package/dist/services/token.d.ts.map +1 -0
  68. package/dist/services/token.js +176 -0
  69. package/dist/types/auth.d.ts +64 -0
  70. package/dist/types/auth.d.ts.map +1 -0
  71. package/dist/types/auth.js +2 -0
  72. package/dist/types/error.d.ts +11 -0
  73. package/dist/types/error.d.ts.map +1 -0
  74. package/dist/types/error.js +2 -0
  75. package/dist/types/request.d.ts +25 -0
  76. package/dist/types/request.d.ts.map +1 -0
  77. package/dist/types/request.js +2 -0
  78. package/dist/types/response.d.ts +44 -0
  79. package/dist/types/response.d.ts.map +1 -0
  80. package/dist/types/response.js +2 -0
  81. package/dist/types/token.d.ts +43 -0
  82. package/dist/types/token.d.ts.map +1 -0
  83. package/dist/types/token.js +2 -0
  84. package/dist/utils/constants.d.ts +41 -0
  85. package/dist/utils/constants.d.ts.map +1 -0
  86. package/dist/utils/constants.js +73 -0
  87. package/package.json +57 -0
package/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Jason Watmore
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,164 @@
1
+ # _Request_
2
+
3
+ [![GitHub stars](https://img.shields.io/github/stars/forgepack/request?style=social)](https://github.com/forgepack/request)
4
+
5
+ ![Node.js](https://img.shields.io/badge/Node.js-22.20.0-339933?logo=node.js)
6
+ ![npm](https://img.shields.io/badge/npm-11.6.2-CB3837?logo=npm)
7
+ ![React](https://img.shields.io/badge/React-19.2.0-blue?logo=react)
8
+ ![TypeScript](https://img.shields.io/badge/TypeScript-5.9.3-blue?logo=typescript)
9
+
10
+ ## Start a new project
11
+
12
+ ```bash
13
+ mkdir package-name
14
+ cd package-name
15
+ npm init
16
+ ```
17
+
18
+ > .json file created:
19
+ ```json
20
+ {
21
+ "name": "package-name",
22
+ "version": "1.0.0",
23
+ "description": "Package Description",
24
+ "main": "index.js",
25
+ "scripts": {
26
+ "test": "echo \"Error: no test specified\" && exit 1"
27
+ },
28
+ "keywords": ["palavra-chave1", "palavra-chave2"],
29
+ "author": "Name",
30
+ "license": "MIT"
31
+ }
32
+ ```
33
+
34
+ ## Publicar no _npm_
35
+
36
+ ```bash
37
+ # Login no npm
38
+ npm login
39
+ # Constrói
40
+ npm run build
41
+ # Simula publicação
42
+ npm pack
43
+ # Publicar o pacote, na primeira vez
44
+ npm publish --access public
45
+ ```
46
+
47
+ ## Atualizar versões
48
+ > Quando fizer mudanças:
49
+ ```bash
50
+ npm version patch # 1.0.0 -> 1.0.1
51
+ npm version minor # 1.0.0 -> 1.1.0
52
+ npm version major # 1.0.0 -> 2.0.0
53
+
54
+ npm publish
55
+ ```
56
+
57
+ ## Publish at
58
+ ```bash
59
+ https://github.com/forgepack
60
+ https://www.npmjs.com/org/forgepack
61
+ https://dev.to/
62
+ https://codesandbox.io/
63
+ https://stackblitz.com/
64
+ ```
65
+
66
+ ## Uso pelo consumidor (Vite, React, Next, Node, etc.)
67
+
68
+ ### 📦 **Instalação**
69
+
70
+ ```bash
71
+ npm install @forgepack/request
72
+ ```
73
+
74
+ ### ⚙️ **Configuração Básica**
75
+
76
+ ```typescript
77
+ // 1. Configure o cliente da API
78
+ import { createApiClient } from "@forgepack/request"
79
+
80
+ export const api = createApiClient({
81
+ baseURL: "https://api.meuservico.com",
82
+ onUnauthorized: () => window.location.href = "/login",
83
+ onForbidden: () => window.location.href = "/notAllowed"
84
+ })
85
+
86
+ // 2. Configure o provedor de autenticação
87
+ import { AuthProvider } from '@forgepack/request'
88
+
89
+ function App() {
90
+ return (
91
+ <AuthProvider api={api}>
92
+ <YourApp />
93
+ </AuthProvider>
94
+ )
95
+ }
96
+ ```
97
+
98
+ ### 🚀 **Principais Recursos**
99
+
100
+ - **🔐 Autenticação JWT** - Login automático com interceptors
101
+ - **🛡️ Proteção de Rotas** - Componente `RequireAuth` baseado em roles
102
+ - **📊 Hook de Requisições** - `useRequest` com paginação e busca
103
+ - **⚡ Operações CRUD** - Funções prontas para create, read, update, delete
104
+ - **🔑 Gerenciamento de Tokens** - Validação e decodificação automática
105
+ - **📱 Responsivo** - Estados de loading, erro e paginação
106
+
107
+ ### 📚 **Complete Documentation**
108
+
109
+ For detailed examples, usage guides, and API references, please visit:
110
+ **[Complete Documentation](./docs/README.md)**
111
+
112
+ ### 🎯 **Quick Example**
113
+
114
+ ```tsx
115
+ // Authentication hook
116
+ const { loginUser, isAuthenticated, role } = useAuth()
117
+
118
+ // Hook for paginated requests
119
+ const { response, loading, error } = useRequest(api, 'users', {
120
+ page: 0, size: 10, value: 'busca'
121
+ })
122
+
123
+ // Route protection
124
+ <RequireAuth allowedRoles={['ADMIN']}>
125
+ <AdminPanel />
126
+ </RequireAuth>
127
+ ```
128
+
129
+ ## Developers
130
+ > [Gadelha TI](https://github.com/gadelhati)
131
+
132
+ ## **License**
133
+
134
+ > This project is licensed under the **MIT License** - see the [MIT LICENSE]( https://choosealicense.com/licenses/mit/) file for details.
135
+
136
+ ```text
137
+ MIT License
138
+
139
+ Copyright (c) 2024 Gadelha TI
140
+
141
+ Permission is hereby granted, free of charge, to any person obtaining a copy
142
+ of this software and associated documentation files (the "Software"), to deal
143
+ in the Software without restriction, including without limitation the rights
144
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
145
+ copies of the Software, and to permit persons to whom the Software is
146
+ furnished to do so, subject to the following conditions:
147
+
148
+ The above copyright notice and this permission notice shall be included in all
149
+ copies or substantial portions of the Software.
150
+
151
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
152
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
153
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
154
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
155
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
156
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
157
+ SOFTWARE.
158
+ ```
159
+
160
+ <div align="center">
161
+
162
+ Request
163
+
164
+ **⭐ Did you like the project? Leave a star! ⭐**
@@ -0,0 +1,8 @@
1
+ import { AxiosInstance } from "axios";
2
+ export type ApiClientOptions = {
3
+ baseURL: string;
4
+ onUnauthorized?: () => void;
5
+ onForbidden?: () => void;
6
+ };
7
+ export declare const createApiClient: (options: ApiClientOptions) => AxiosInstance;
8
+ //# sourceMappingURL=api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/api/api.tsx"],"names":[],"mappings":"AAAA,OAAc,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AAG5C,MAAM,MAAM,gBAAgB,GAAG;IAC3B,OAAO,EAAE,MAAM,CAAA;IACf,cAAc,CAAC,EAAE,MAAM,IAAI,CAAA;IAC3B,WAAW,CAAC,EAAE,MAAM,IAAI,CAAA;CAC3B,CAAA;AAED,eAAO,MAAM,eAAe,GAAI,SAAS,gBAAgB,KAAG,aA4B3D,CAAA"}
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createApiClient = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const token_1 = require("../service/token");
9
+ const createApiClient = (options) => {
10
+ const api = axios_1.default.create({
11
+ baseURL: options.baseURL,
12
+ headers: { 'content-type': 'application/json' }
13
+ });
14
+ api.interceptors.request.use(async (config) => {
15
+ var _a;
16
+ const token = (_a = (0, token_1.getToken)()) === null || _a === void 0 ? void 0 : _a.accessToken;
17
+ if (token) {
18
+ config.headers.Authorization = `Bearer ${token}`;
19
+ }
20
+ return config;
21
+ });
22
+ api.interceptors.response.use((response) => response, (error) => {
23
+ var _a, _b, _c, _d;
24
+ if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 401) {
25
+ (0, token_1.removeToken)();
26
+ (_b = options.onUnauthorized) === null || _b === void 0 ? void 0 : _b.call(options);
27
+ }
28
+ if (((_c = error.response) === null || _c === void 0 ? void 0 : _c.status) === 403) {
29
+ (_d = options.onForbidden) === null || _d === void 0 ? void 0 : _d.call(options);
30
+ }
31
+ return Promise.reject(error);
32
+ });
33
+ return api;
34
+ };
35
+ exports.createApiClient = createApiClient;
@@ -0,0 +1,30 @@
1
+ import { AxiosInstance } from "axios";
2
+ /**
3
+ * Opções de configuração para o cliente da API
4
+ * @interface ApiClientOptions
5
+ */
6
+ export type ApiClientOptions = {
7
+ /** URL base da API */
8
+ baseURL: string;
9
+ /** Callback executado quando recebe erro 401 (Unauthorized) */
10
+ onUnauthorized?: () => void;
11
+ /** Callback executado quando recebe erro 403 (Forbidden) */
12
+ onForbidden?: () => void;
13
+ };
14
+ /**
15
+ * Cria uma instância configurada do cliente Axios com interceptors para autenticação JWT
16
+ *
17
+ * @param options - Opções de configuração do cliente
18
+ * @returns Instância configurada do Axios com interceptors de request/response
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * const api = createApiClient({
23
+ * baseURL: 'https://api.exemplo.com',
24
+ * onUnauthorized: () => window.location.href = '/login',
25
+ * onForbidden: () => alert('Acesso negado')
26
+ * })
27
+ * ```
28
+ */
29
+ export declare const createApiClient: (options: ApiClientOptions) => AxiosInstance;
30
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"AAAA,OAAc,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AAG5C;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC3B,sBAAsB;IACtB,OAAO,EAAE,MAAM,CAAA;IACf,+DAA+D;IAC/D,cAAc,CAAC,EAAE,MAAM,IAAI,CAAA;IAC3B,4DAA4D;IAC5D,WAAW,CAAC,EAAE,MAAM,IAAI,CAAA;CAC3B,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,eAAe,GAAI,SAAS,gBAAgB,KAAG,aA4B3D,CAAA"}
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createApiClient = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const token_1 = require("../services/token");
9
+ /**
10
+ * Cria uma instância configurada do cliente Axios com interceptors para autenticação JWT
11
+ *
12
+ * @param options - Opções de configuração do cliente
13
+ * @returns Instância configurada do Axios com interceptors de request/response
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const api = createApiClient({
18
+ * baseURL: 'https://api.exemplo.com',
19
+ * onUnauthorized: () => window.location.href = '/login',
20
+ * onForbidden: () => alert('Acesso negado')
21
+ * })
22
+ * ```
23
+ */
24
+ const createApiClient = (options) => {
25
+ const api = axios_1.default.create({
26
+ baseURL: options.baseURL,
27
+ headers: { 'content-type': 'application/json' }
28
+ });
29
+ api.interceptors.request.use(async (config) => {
30
+ var _a;
31
+ const token = (_a = (0, token_1.getToken)()) === null || _a === void 0 ? void 0 : _a.accessToken;
32
+ if (token) {
33
+ config.headers.Authorization = `Bearer ${token}`;
34
+ }
35
+ return config;
36
+ });
37
+ api.interceptors.response.use((response) => response, (error) => {
38
+ var _a, _b, _c, _d;
39
+ if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 401) {
40
+ (0, token_1.removeToken)();
41
+ (_b = options.onUnauthorized) === null || _b === void 0 ? void 0 : _b.call(options);
42
+ }
43
+ if (((_c = error.response) === null || _c === void 0 ? void 0 : _c.status) === 403) {
44
+ (_d = options.onForbidden) === null || _d === void 0 ? void 0 : _d.call(options);
45
+ }
46
+ return Promise.reject(error);
47
+ });
48
+ return api;
49
+ };
50
+ exports.createApiClient = createApiClient;
@@ -0,0 +1,8 @@
1
+ export interface Auth {
2
+ readonly accessToken: string;
3
+ refreshToken: string;
4
+ tokenType: string;
5
+ role: string[];
6
+ }
7
+ export declare const initialAuth: Auth;
8
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/component/auth.tsx"],"names":[],"mappings":"AAAA,MAAM,WAAW,IAAI;IACjB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,EAAE,CAAA;CACd;AAED,eAAO,MAAM,WAAW,EAAG,IAK1B,CAAA"}
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initialAuth = void 0;
4
+ exports.initialAuth = {
5
+ accessToken: '',
6
+ refreshToken: '',
7
+ tokenType: '',
8
+ role: []
9
+ };
@@ -0,0 +1,6 @@
1
+ export interface ErrorMessage {
2
+ field: string;
3
+ message: string;
4
+ }
5
+ export declare const initialErrorMessage: ErrorMessage;
6
+ //# sourceMappingURL=errorMessage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errorMessage.d.ts","sourceRoot":"","sources":["../../src/component/errorMessage.tsx"],"names":[],"mappings":"AAAA,MAAM,WAAW,YAAY;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAA;CAClB;AAED,eAAO,MAAM,mBAAmB,EAAE,YAGjC,CAAA"}
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initialErrorMessage = void 0;
4
+ exports.initialErrorMessage = {
5
+ field: '',
6
+ message: ''
7
+ };
@@ -0,0 +1,13 @@
1
+ interface Sort {
2
+ key: string;
3
+ order: 'ASC' | 'DESC';
4
+ }
5
+ export interface Search {
6
+ value?: string;
7
+ page?: number;
8
+ size?: number;
9
+ sort?: Sort;
10
+ }
11
+ export declare const initialSearch: Search;
12
+ export {};
13
+ //# sourceMappingURL=request.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../src/component/request.tsx"],"names":[],"mappings":"AAAA,UAAU,IAAI;IACV,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,KAAK,GAAG,MAAM,CAAA;CACxB;AAED,MAAM,WAAW,MAAM;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAA;CACd;AAED,eAAO,MAAM,aAAa,EAAE,MAQ3B,CAAA"}
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initialSearch = void 0;
4
+ exports.initialSearch = {
5
+ value: '',
6
+ page: 0,
7
+ size: 15,
8
+ sort: {
9
+ key: 'id',
10
+ order: 'ASC',
11
+ }
12
+ };
@@ -0,0 +1,13 @@
1
+ interface PageInfo {
2
+ size: number;
3
+ number: number;
4
+ totalElements: number;
5
+ totalPages: number;
6
+ }
7
+ export interface Page<T = unknown> {
8
+ content: T[];
9
+ page: PageInfo;
10
+ }
11
+ export declare const initialPage: Page;
12
+ export {};
13
+ //# sourceMappingURL=response.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response.d.ts","sourceRoot":"","sources":["../../src/component/response.tsx"],"names":[],"mappings":"AAAA,UAAU,QAAQ;IACd,IAAI,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,MAAM,CAAA;CAClB;AASD,MAAM,WAAW,IAAI,CAAC,CAAC,GAAG,OAAO;IAChC,OAAO,EAAE,CAAC,EAAE,CAAC;IACb,IAAI,EAAE,QAAQ,CAAA;CACd;AAED,eAAO,MAAM,WAAW,EAAE,IAGzB,CAAA"}
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initialPage = void 0;
4
+ const initialPageInfo = {
5
+ size: 0,
6
+ number: 0,
7
+ totalElements: 0,
8
+ totalPages: 0
9
+ };
10
+ exports.initialPage = {
11
+ content: [],
12
+ page: initialPageInfo
13
+ };
@@ -0,0 +1,32 @@
1
+ export interface Token {
2
+ header: {
3
+ alg: string;
4
+ typ: string;
5
+ };
6
+ payload: {
7
+ jti: string;
8
+ iss: string;
9
+ iat: string;
10
+ nbf: string;
11
+ exp: string;
12
+ sub: string;
13
+ aud: string;
14
+ };
15
+ signature: string;
16
+ }
17
+ export interface Header {
18
+ alg: string;
19
+ typ: string;
20
+ }
21
+ export interface Payload {
22
+ jti: string;
23
+ iss: string;
24
+ iat: string;
25
+ nbf: string;
26
+ exp: string;
27
+ sub: string;
28
+ aud: string;
29
+ }
30
+ export declare const initialHeader: Header;
31
+ export declare const initialPayload: Payload;
32
+ //# sourceMappingURL=token.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../src/component/token.tsx"],"names":[],"mappings":"AAAA,MAAM,WAAW,KAAK;IAClB,MAAM,EAAE;QACJ,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,MAAM,CAAC;KACf,CAAC;IACF,OAAO,EAAE;QACL,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,MAAM,CAAC;KACf,CAAC;IACF,SAAS,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,WAAW,MAAM;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAA;CACd;AAED,MAAM,WAAW,OAAO;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAA;CACd;AAED,eAAO,MAAM,aAAa,EAAE,MAG3B,CAAA;AAED,eAAO,MAAM,cAAc,EAAE,OAQ5B,CAAA"}
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initialPayload = exports.initialHeader = void 0;
4
+ exports.initialHeader = {
5
+ alg: '',
6
+ typ: ''
7
+ };
8
+ exports.initialPayload = {
9
+ jti: '',
10
+ iss: '',
11
+ iat: '',
12
+ nbf: '',
13
+ exp: '',
14
+ sub: '',
15
+ aud: ''
16
+ };
@@ -0,0 +1,13 @@
1
+ import { Auth } from '../component/auth';
2
+ import { AxiosInstance } from 'axios';
3
+ export interface AuthContextType extends Auth {
4
+ loginUser: (credentials: any) => Promise<any>;
5
+ logoutUser: () => void;
6
+ isAuthenticated: boolean;
7
+ }
8
+ export declare const AuthContext: import("react").Context<AuthContextType>;
9
+ export declare const AuthProvider: ({ api, children }: {
10
+ api: AxiosInstance;
11
+ children: React.ReactNode;
12
+ }) => import("react/jsx-runtime").JSX.Element;
13
+ //# sourceMappingURL=useProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useProvider.d.ts","sourceRoot":"","sources":["../../src/hook/useProvider.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAe,MAAM,mBAAmB,CAAA;AAErD,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AAErC,MAAM,WAAW,eAAgB,SAAQ,IAAI;IACzC,SAAS,EAAE,CAAC,WAAW,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,CAAA;IAC7C,UAAU,EAAE,MAAM,IAAI,CAAA;IACtB,eAAe,EAAE,OAAO,CAAA;CAC3B;AAED,eAAO,MAAM,WAAW,0CAAiE,CAAA;AAEzF,eAAO,MAAM,YAAY,GAAI,mBAAmB;IAC5C,GAAG,EAAE,aAAa,CAAA;IAClB,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;CAC5B,4CAkDA,CAAA"}
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthProvider = exports.AuthContext = void 0;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const react_1 = require("react");
6
+ const token_1 = require("../service/token");
7
+ const auth_1 = require("../component/auth");
8
+ const crud_1 = require("../service/crud");
9
+ exports.AuthContext = (0, react_1.createContext)(auth_1.initialAuth);
10
+ const AuthProvider = ({ api, children }) => {
11
+ const [state, setState] = (0, react_1.useState)(() => (0, token_1.isValidToken)() ? (0, token_1.getToken)() : auth_1.initialAuth);
12
+ const loginUser = (0, react_1.useCallback)(async (credentials) => {
13
+ const result = await (0, crud_1.login)(api, '/auth/login', credentials);
14
+ if (!Array.isArray(result)) {
15
+ setState(result);
16
+ return { success: true, data: result };
17
+ }
18
+ return { success: false, errors: result };
19
+ }, []);
20
+ const logoutUser = (0, react_1.useCallback)(() => {
21
+ (0, crud_1.logout)();
22
+ setState(auth_1.initialAuth);
23
+ window.location.href = '/login';
24
+ }, []);
25
+ // Verifica token expirado a cada minuto
26
+ (0, react_1.useEffect)(() => {
27
+ const interval = setInterval(() => {
28
+ if (state.accessToken && !(0, token_1.isValidToken)()) {
29
+ logoutUser();
30
+ }
31
+ }, 60000);
32
+ return () => clearInterval(interval);
33
+ }, [state.accessToken, logoutUser]);
34
+ // Escuta mudanças no localStorage (ex.: logout em outra aba)
35
+ (0, react_1.useEffect)(() => {
36
+ const handleStorageChange = (e) => {
37
+ if (e.key === 'token') {
38
+ if (!e.newValue || !(0, token_1.isValidToken)()) {
39
+ setState(auth_1.initialAuth);
40
+ }
41
+ else {
42
+ setState((0, token_1.getToken)());
43
+ }
44
+ }
45
+ };
46
+ window.addEventListener('storage', handleStorageChange);
47
+ return () => window.removeEventListener('storage', handleStorageChange);
48
+ }, []);
49
+ return ((0, jsx_runtime_1.jsx)(exports.AuthContext.Provider, { value: { ...state, loginUser, logoutUser, isAuthenticated: (0, token_1.isValidToken)() }, children: children }));
50
+ };
51
+ exports.AuthProvider = AuthProvider;
@@ -0,0 +1,11 @@
1
+ import { ErrorMessage } from '../component/errorMessage';
2
+ import { Page } from '../component/response';
3
+ import { Search } from '../component/request';
4
+ import { AxiosInstance } from 'axios';
5
+ export declare const useRequest: (api: AxiosInstance, endpoint: string, search?: Search) => {
6
+ response: Page<unknown>;
7
+ error: ErrorMessage[];
8
+ loading: boolean;
9
+ request: () => Promise<void>;
10
+ };
11
+ //# sourceMappingURL=useRequest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRequest.d.ts","sourceRoot":"","sources":["../../src/hook/useRequest.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAuB,MAAM,2BAA2B,CAAA;AAC7E,OAAO,EAAe,IAAI,EAAE,MAAM,uBAAuB,CAAA;AACzD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAE7C,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AAErC,eAAO,MAAM,UAAU,GAAI,KAAK,aAAa,EAAE,UAAU,MAAM,EAAE,SAAS,MAAM;;;;;CA8B/E,CAAA"}
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useRequest = void 0;
4
+ const react_1 = require("react");
5
+ const errorMessage_1 = require("../component/errorMessage");
6
+ const response_1 = require("../component/response");
7
+ const fetchPage_1 = require("../service/fetchPage");
8
+ const useRequest = (api, endpoint, search) => {
9
+ const [response, setResponse] = (0, react_1.useState)(response_1.initialPage);
10
+ const [error, setError] = (0, react_1.useState)([errorMessage_1.initialErrorMessage]);
11
+ const [loading, setLoading] = (0, react_1.useState)(false);
12
+ const abortControllerRef = (0, react_1.useRef)(null);
13
+ const request = (0, react_1.useCallback)(async () => {
14
+ var _a;
15
+ (_a = abortControllerRef.current) === null || _a === void 0 ? void 0 : _a.abort();
16
+ const controller = new AbortController();
17
+ abortControllerRef.current = controller;
18
+ try {
19
+ setLoading(true);
20
+ setError([errorMessage_1.initialErrorMessage]);
21
+ const data = await (0, fetchPage_1.FetchPage)(api, endpoint, search, controller.signal);
22
+ setResponse(data);
23
+ }
24
+ catch (requestError) {
25
+ setError([requestError]);
26
+ }
27
+ finally {
28
+ setLoading(false);
29
+ abortControllerRef.current = null;
30
+ }
31
+ }, [endpoint, search]);
32
+ (0, react_1.useEffect)(() => {
33
+ request();
34
+ return () => { var _a; return (_a = abortControllerRef.current) === null || _a === void 0 ? void 0 : _a.abort(); };
35
+ }, [request]);
36
+ return { response, error, loading, request };
37
+ };
38
+ exports.useRequest = useRequest;
@@ -0,0 +1,4 @@
1
+ import { AuthContextType } from './useProvider';
2
+ export declare const useAuth: () => AuthContextType;
3
+ export declare const RequireAuth: ({ allowedRoles }: any) => import("react/jsx-runtime").JSX.Element;
4
+ //# sourceMappingURL=useRequireAuth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRequireAuth.d.ts","sourceRoot":"","sources":["../../src/hook/useRequireAuth.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAe,eAAe,EAAE,MAAM,eAAe,CAAA;AAE5D,eAAO,MAAM,OAAO,QAAO,eAE1B,CAAA;AAED,eAAO,MAAM,WAAW,GAAI,kBAAkB,GAAG,4CAWhD,CAAA"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RequireAuth = exports.useAuth = void 0;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const react_1 = require("react");
6
+ const react_router_dom_1 = require("react-router-dom");
7
+ const useProvider_1 = require("./useProvider");
8
+ const useAuth = () => {
9
+ return (0, react_1.useContext)(useProvider_1.AuthContext);
10
+ };
11
+ exports.useAuth = useAuth;
12
+ const RequireAuth = ({ allowedRoles }) => {
13
+ const { role, accessToken } = (0, exports.useAuth)();
14
+ const location = (0, react_router_dom_1.useLocation)();
15
+ return ((role === null || role === void 0 ? void 0 : role.find((role) => allowedRoles === null || allowedRoles === void 0 ? void 0 : allowedRoles.includes(role)))
16
+ ? (0, jsx_runtime_1.jsx)(react_router_dom_1.Outlet, {})
17
+ : accessToken
18
+ ? (0, jsx_runtime_1.jsx)(react_router_dom_1.Navigate, { to: '/notAllowed', state: { from: location }, replace: true })
19
+ : (0, jsx_runtime_1.jsx)(react_router_dom_1.Navigate, { to: '/login', state: { from: location }, replace: true }));
20
+ };
21
+ exports.RequireAuth = RequireAuth;