@hidrografico/request 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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Instituto Hidrográfico]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,275 @@
1
+ # _Request_
2
+
3
+ ## Inicializar o projeto
4
+
5
+ ```bash
6
+ mkdir meu-pacote
7
+ cd meu-pacote
8
+ npm init
9
+ ```
10
+
11
+ > Arquivo .json criado:
12
+ ```json
13
+ {
14
+ "name": "meu-pacote-unico",
15
+ "version": "1.0.0",
16
+ "description": "Descrição do pacote",
17
+ "main": "index.js",
18
+ "scripts": {
19
+ "test": "echo \"Error: no test specified\" && exit 1"
20
+ },
21
+ "keywords": ["palavra-chave1", "palavra-chave2"],
22
+ "author": "Seu Nome",
23
+ "license": "MIT"
24
+ }
25
+ ```
26
+
27
+ ## Publicar no _npm_
28
+
29
+ ```bash
30
+ # Login no npm
31
+ npm login
32
+ # Publicar o pacote, na primeira vez
33
+ npm publish --access public
34
+ ```
35
+
36
+ ## Atualizar versões
37
+ > Quando fizer mudanças:
38
+ ```bash
39
+ npm version patch # 1.0.0 -> 1.0.1
40
+ npm version minor # 1.0.0 -> 1.1.0
41
+ npm version major # 1.0.0 -> 2.0.0
42
+
43
+ npm publish
44
+ ```
45
+
46
+ ## Uso pelo consumidor (Vite, React, Next, Node, etc.)
47
+
48
+ ```javascript
49
+ import { createApiClient } from "@seu-pacote/api"
50
+
51
+ export const api = createApiClient({
52
+ baseURL: "https://api.meuservico.com",
53
+ onUnauthorized: () => {
54
+ window.location.href = "/login"
55
+ },
56
+ onForbidden: () => {
57
+ window.location.href = "/notAllowed"
58
+ }
59
+ })
60
+ ```
61
+
62
+ ## Developers
63
+ > [Gadelha TI](https://github.com/gadelhati)
64
+
65
+ ## Licence
66
+ > [Apache License 2.0](https://choosealicense.com/licenses/apache-2.0/)
67
+ ```
68
+ Apache License
69
+ Version 2.0, January 2004
70
+ http://www.apache.org/licenses/
71
+
72
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
73
+
74
+ 1. Definitions.
75
+
76
+ "License" shall mean the terms and conditions for use, reproduction,
77
+ and distribution as defined by Sections 1 through 9 of this document.
78
+
79
+ "Licensor" shall mean the copyright owner or entity authorized by
80
+ the copyright owner that is granting the License.
81
+
82
+ "Legal Entity" shall mean the union of the acting entity and all
83
+ other entities that control, are controlled by, or are under common
84
+ control with that entity. For the purposes of this definition,
85
+ "control" means (i) the power, direct or indirect, to cause the
86
+ direction or management of such entity, whether by contract or
87
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
88
+ outstanding shares, or (iii) beneficial ownership of such entity.
89
+
90
+ "You" (or "Your") shall mean an individual or Legal Entity
91
+ exercising permissions granted by this License.
92
+
93
+ "Source" form shall mean the preferred form for making modifications,
94
+ including but not limited to software source code, documentation
95
+ source, and configuration files.
96
+
97
+ "Object" form shall mean any form resulting from mechanical
98
+ transformation or translation of a Source form, including but
99
+ not limited to compiled object code, generated documentation,
100
+ and conversions to other media types.
101
+
102
+ "Work" shall mean the work of authorship, whether in Source or
103
+ Object form, made available under the License, as indicated by a
104
+ copyright notice that is included in or attached to the work
105
+ (an example is provided in the Appendix below).
106
+
107
+ "Derivative Works" shall mean any work, whether in Source or Object
108
+ form, that is based on (or derived from) the Work and for which the
109
+ editorial revisions, annotations, elaborations, or other modifications
110
+ represent, as a whole, an original work of authorship. For the purposes
111
+ of this License, Derivative Works shall not include works that remain
112
+ separable from, or merely link (or bind by name) to the interfaces of,
113
+ the Work and Derivative Works thereof.
114
+
115
+ "Contribution" shall mean any work of authorship, including
116
+ the original version of the Work and any modifications or additions
117
+ to that Work or Derivative Works thereof, that is intentionally
118
+ submitted to Licensor for inclusion in the Work by the copyright owner
119
+ or by an individual or Legal Entity authorized to submit on behalf of
120
+ the copyright owner. For the purposes of this definition, "submitted"
121
+ means any form of electronic, verbal, or written communication sent
122
+ to the Licensor or its representatives, including but not limited to
123
+ communication on electronic mailing lists, source code control systems,
124
+ and issue tracking systems that are managed by, or on behalf of, the
125
+ Licensor for the purpose of discussing and improving the Work, but
126
+ excluding communication that is conspicuously marked or otherwise
127
+ designated in writing by the copyright owner as "Not a Contribution."
128
+
129
+ "Contributor" shall mean Licensor and any individual or Legal Entity
130
+ on behalf of whom a Contribution has been received by Licensor and
131
+ subsequently incorporated within the Work.
132
+
133
+ 2. Grant of Copyright License. Subject to the terms and conditions of
134
+ this License, each Contributor hereby grants to You a perpetual,
135
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
136
+ copyright license to reproduce, prepare Derivative Works of,
137
+ publicly display, publicly perform, sublicense, and distribute the
138
+ Work and such Derivative Works in Source or Object form.
139
+
140
+ 3. Grant of Patent License. Subject to the terms and conditions of
141
+ this License, each Contributor hereby grants to You a perpetual,
142
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
143
+ (except as stated in this section) patent license to make, have made,
144
+ use, offer to sell, sell, import, and otherwise transfer the Work,
145
+ where such license applies only to those patent claims licensable
146
+ by such Contributor that are necessarily infringed by their
147
+ Contribution(s) alone or by combination of their Contribution(s)
148
+ with the Work to which such Contribution(s) was submitted. If You
149
+ institute patent litigation against any entity (including a
150
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
151
+ or a Contribution incorporated within the Work constitutes direct
152
+ or contributory patent infringement, then any patent licenses
153
+ granted to You under this License for that Work shall terminate
154
+ as of the date such litigation is filed.
155
+
156
+ 4. Redistribution. You may reproduce and distribute copies of the
157
+ Work or Derivative Works thereof in any medium, with or without
158
+ modifications, and in Source or Object form, provided that You
159
+ meet the following conditions:
160
+
161
+ (a) You must give any other recipients of the Work or
162
+ Derivative Works a copy of this License; and
163
+
164
+ (b) You must cause any modified files to carry prominent notices
165
+ stating that You changed the files; and
166
+
167
+ (c) You must retain, in the Source form of any Derivative Works
168
+ that You distribute, all copyright, patent, trademark, and
169
+ attribution notices from the Source form of the Work,
170
+ excluding those notices that do not pertain to any part of
171
+ the Derivative Works; and
172
+
173
+ (d) If the Work includes a "NOTICE" text file as part of its
174
+ distribution, then any Derivative Works that You distribute must
175
+ include a readable copy of the attribution notices contained
176
+ within such NOTICE file, excluding those notices that do not
177
+ pertain to any part of the Derivative Works, in at least one
178
+ of the following places: within a NOTICE text file distributed
179
+ as part of the Derivative Works; within the Source form or
180
+ documentation, if provided along with the Derivative Works; or,
181
+ within a display generated by the Derivative Works, if and
182
+ wherever such third-party notices normally appear. The contents
183
+ of the NOTICE file are for informational purposes only and
184
+ do not modify the License. You may add Your own attribution
185
+ notices within Derivative Works that You distribute, alongside
186
+ or as an addendum to the NOTICE text from the Work, provided
187
+ that such additional attribution notices cannot be construed
188
+ as modifying the License.
189
+
190
+ You may add Your own copyright statement to Your modifications and
191
+ may provide additional or different license terms and conditions
192
+ for use, reproduction, or distribution of Your modifications, or
193
+ for any such Derivative Works as a whole, provided Your use,
194
+ reproduction, and distribution of the Work otherwise complies with
195
+ the conditions stated in this License.
196
+
197
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
198
+ any Contribution intentionally submitted for inclusion in the Work
199
+ by You to the Licensor shall be under the terms and conditions of
200
+ this License, without any additional terms or conditions.
201
+ Notwithstanding the above, nothing herein shall supersede or modify
202
+ the terms of any separate license agreement you may have executed
203
+ with Licensor regarding such Contributions.
204
+
205
+ 6. Trademarks. This License does not grant permission to use the trade
206
+ names, trademarks, service marks, or product names of the Licensor,
207
+ except as required for reasonable and customary use in describing the
208
+ origin of the Work and reproducing the content of the NOTICE file.
209
+
210
+ 7. Disclaimer of Warranty. Unless required by applicable law or
211
+ agreed to in writing, Licensor provides the Work (and each
212
+ Contributor provides its Contributions) on an "AS IS" BASIS,
213
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
214
+ implied, including, without limitation, any warranties or conditions
215
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
216
+ PARTICULAR PURPOSE. You are solely responsible for determining the
217
+ appropriateness of using or redistributing the Work and assume any
218
+ risks associated with Your exercise of permissions under this License.
219
+
220
+ 8. Limitation of Liability. In no event and under no legal theory,
221
+ whether in tort (including negligence), contract, or otherwise,
222
+ unless required by applicable law (such as deliberate and grossly
223
+ negligent acts) or agreed to in writing, shall any Contributor be
224
+ liable to You for damages, including any direct, indirect, special,
225
+ incidental, or consequential damages of any character arising as a
226
+ result of this License or out of the use or inability to use the
227
+ Work (including but not limited to damages for loss of goodwill,
228
+ work stoppage, computer failure or malfunction, or any and all
229
+ other commercial damages or losses), even if such Contributor
230
+ has been advised of the possibility of such damages.
231
+
232
+ 9. Accepting Warranty or Additional Liability. While redistributing
233
+ the Work or Derivative Works thereof, You may choose to offer,
234
+ and charge a fee for, acceptance of support, warranty, indemnity,
235
+ or other liability obligations and/or rights consistent with this
236
+ License. However, in accepting such obligations, You may act only
237
+ on Your own behalf and on Your sole responsibility, not on behalf
238
+ of any other Contributor, and only if You agree to indemnify,
239
+ defend, and hold each Contributor harmless for any liability
240
+ incurred by, or claims asserted against, such Contributor by reason
241
+ of your accepting any such warranty or additional liability.
242
+
243
+ END OF TERMS AND CONDITIONS
244
+
245
+ APPENDIX: How to apply the Apache License to your work.
246
+
247
+ To apply the Apache License to your work, attach the following
248
+ boilerplate notice, with the fields enclosed by brackets "[]"
249
+ replaced with your own identifying information. (Don't include
250
+ the brackets!) The text should be enclosed in the appropriate
251
+ comment syntax for the file format. We also recommend that a
252
+ file or class name and description of purpose be included on the
253
+ same "printed page" as the copyright notice for easier
254
+ identification within third-party archives.
255
+
256
+ Copyright [2025] [Instituto Hidrográfico]
257
+
258
+ Licensed under the Apache License, Version 2.0 (the "License");
259
+ you may not use this file except in compliance with the License.
260
+ You may obtain a copy of the License at
261
+
262
+ http://www.apache.org/licenses/LICENSE-2.0
263
+
264
+ Unless required by applicable law or agreed to in writing, software
265
+ distributed under the License is distributed on an "AS IS" BASIS,
266
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
267
+ See the License for the specific language governing permissions and
268
+ limitations under the License.
269
+ ```
270
+
271
+ <div align="center">
272
+
273
+ Request
274
+
275
+ **⭐ Did you like the project? Leave a star! ⭐**
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@hidrografico/request",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "homepage": "https://github.com/hidrografico/request#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/hidrografico/request/issues"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/hidrografico/request.git"
12
+ },
13
+ "license": "Apache License 2.0",
14
+ "keywords": [
15
+ "palavra-chave1",
16
+ "palavra-chave2"
17
+ ],
18
+ "author": "Marcelo Gadelha",
19
+ "type": "commonjs",
20
+ "main": "index.js",
21
+ "scripts": {
22
+ "test": "echo \"Error: no test specified\" && exit 1"
23
+ },
24
+ "peerDependencies": {
25
+ "axios": "^1.13.2",
26
+ "react": "^19.2.3"
27
+ },
28
+ "devDependencies": {
29
+ "@types/react": "^19.2.9",
30
+ "@types/react-dom": "^19.2.3"
31
+ },
32
+ "dependencies": {
33
+ "react-router-dom": "^7.12.0"
34
+ }
35
+ }
@@ -0,0 +1,38 @@
1
+ import axios, { AxiosInstance } from "axios"
2
+ import { getToken, removeToken } from "../service/token"
3
+
4
+ export type ApiClientOptions = {
5
+ baseURL: string
6
+ onUnauthorized?: () => void
7
+ onForbidden?: () => void
8
+ }
9
+
10
+ export const createApiClient = (options: ApiClientOptions): AxiosInstance => {
11
+ const api = axios.create({
12
+ baseURL: options.baseURL,
13
+ headers: { 'content-type': 'application/json' }
14
+ })
15
+
16
+ api.interceptors.request.use(async config => {
17
+ const token = getToken()?.accessToken
18
+ if (token) {
19
+ config.headers!.Authorization = `Bearer ${token}`
20
+ }
21
+ return config
22
+ })
23
+
24
+ api.interceptors.response.use(
25
+ (response) => response,
26
+ (error) => {
27
+ if (error.response?.status === 401) {
28
+ removeToken()
29
+ options.onUnauthorized?.()
30
+ }
31
+ if (error.response?.status === 403) {
32
+ options.onForbidden?.()
33
+ }
34
+ return Promise.reject(error)
35
+ }
36
+ )
37
+ return api
38
+ }
@@ -0,0 +1,13 @@
1
+ export interface Auth {
2
+ readonly accessToken: string,
3
+ refreshToken: string,
4
+ tokenType: string,
5
+ role: []
6
+ }
7
+
8
+ export const initialAuth : Auth = {
9
+ accessToken: '',
10
+ refreshToken: '',
11
+ tokenType: '',
12
+ role: []
13
+ }
@@ -0,0 +1,9 @@
1
+ export interface ErrorMessage {
2
+ field: string,
3
+ message: string
4
+ }
5
+
6
+ export const initialErrorMessage: ErrorMessage = {
7
+ field: '',
8
+ message: ''
9
+ }
@@ -0,0 +1,21 @@
1
+ interface Sort {
2
+ key: string,
3
+ order: 'ASC' | 'DESC'
4
+ }
5
+
6
+ export interface Search {
7
+ value?: string,
8
+ page?: number,
9
+ size?: number,
10
+ sort?: Sort
11
+ }
12
+
13
+ export const initialSearch: Search = {
14
+ value: '',
15
+ page: 0,
16
+ size: 15,
17
+ sort: {
18
+ key: 'id',
19
+ order: 'ASC',
20
+ }
21
+ }
@@ -0,0 +1,23 @@
1
+ interface PageInfo {
2
+ size: number,
3
+ number: number,
4
+ totalElements: number,
5
+ totalPages: number
6
+ }
7
+
8
+ const initialPageInfo: PageInfo = {
9
+ size: 0,
10
+ number: 0,
11
+ totalElements: 0,
12
+ totalPages: 0
13
+ }
14
+
15
+ export interface Page<T = unknown> {
16
+ content: T[],
17
+ page: PageInfo
18
+ }
19
+
20
+ export const initialPage: Page = {
21
+ content: [],
22
+ page: initialPageInfo
23
+ }
@@ -0,0 +1,46 @@
1
+ export interface Token {
2
+ header: {
3
+ alg: string,
4
+ typ: string,
5
+ },
6
+ payload: {
7
+ jti: string, //jsonTokenIdentifier
8
+ iss: string, //issuer
9
+ iat: string, //issuedAt
10
+ nbf: string, //notBefore (Não Antes)
11
+ exp: string, //expiration
12
+ sub: string, //Subject
13
+ aud: string, //Audience
14
+ },
15
+ signature: string
16
+ }
17
+
18
+ export interface Header {
19
+ alg: string,
20
+ typ: string
21
+ }
22
+
23
+ export interface Payload {
24
+ jti: string, //jsonTokenIdentifier
25
+ iss: string, //issuer
26
+ iat: string, //issuedAt
27
+ nbf: string, //notBefore (Não Antes)
28
+ exp: string, //expiration
29
+ sub: string, //Subject
30
+ aud: string //Audience
31
+ }
32
+
33
+ export const initialHeader: Header = {
34
+ alg: '',
35
+ typ: ''
36
+ }
37
+
38
+ export const initialPayload: Payload = {
39
+ jti: '',
40
+ iss: '',
41
+ iat: '',
42
+ nbf: '',
43
+ exp: '',
44
+ sub: '',
45
+ aud: ''
46
+ }
@@ -0,0 +1,68 @@
1
+ import { createContext, useCallback, useEffect, useState } from 'react'
2
+ import { getToken, isValidToken } from '../service/token'
3
+ import { Auth, initialAuth } from '../component/auth'
4
+ import { login, logout } from '../service/crud'
5
+ import { AxiosInstance } from 'axios'
6
+
7
+ interface AuthContextType extends Auth {
8
+ loginUser: (credentials: any) => Promise<any>
9
+ logoutUser: () => void
10
+ isAuthenticated: boolean
11
+ }
12
+
13
+ export const AuthContext = createContext<AuthContextType>(initialAuth as AuthContextType)
14
+
15
+ export const AuthProvider = ({ api, children }: {
16
+ api: AxiosInstance
17
+ children: React.ReactNode
18
+ }) => {
19
+ const [state, setState] = useState<Auth>(() =>
20
+ isValidToken() ? getToken() : initialAuth
21
+ )
22
+
23
+ const loginUser = useCallback(async (credentials: any) => {
24
+ const result = await login(api, '/auth/login', credentials)
25
+
26
+ if (!Array.isArray(result)) {
27
+ setState(result)
28
+ return { success: true, data: result }
29
+ }
30
+
31
+ return { success: false, errors: result }
32
+ }, [])
33
+
34
+ const logoutUser = useCallback(() => {
35
+ logout()
36
+ setState(initialAuth)
37
+ window.location.href = '/login'
38
+ }, [])
39
+ // Verifica token expirado a cada minuto
40
+ useEffect(() => {
41
+ const interval = setInterval(() => {
42
+ if (state.accessToken && !isValidToken()) {
43
+ logoutUser()
44
+ }
45
+ }, 60000)
46
+ return () => clearInterval(interval)
47
+ }, [state.accessToken, logoutUser])
48
+ // Escuta mudanças no localStorage (ex.: logout em outra aba)
49
+ useEffect(() => {
50
+ const handleStorageChange = (e: StorageEvent) => {
51
+ if (e.key === 'token') {
52
+ if (!e.newValue || !isValidToken()) {
53
+ setState(initialAuth)
54
+ } else {
55
+ setState(getToken())
56
+ }
57
+ }
58
+ }
59
+ window.addEventListener('storage', handleStorageChange)
60
+ return () => window.removeEventListener('storage', handleStorageChange)
61
+ }, [])
62
+
63
+ return (
64
+ <AuthContext.Provider value={{ ...state, loginUser, logoutUser, isAuthenticated: isValidToken() }}>
65
+ {children}
66
+ </AuthContext.Provider>
67
+ )
68
+ }
@@ -0,0 +1,38 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react'
2
+ import { ErrorMessage, initialErrorMessage } from '../component/component.errorMessage'
3
+ import { initialPage, Page } from '../component/component.response'
4
+ import { Search } from '../component/component.request'
5
+ import { FetchPage } from '../service/fetchPage'
6
+ import { AxiosInstance } from 'axios'
7
+
8
+ export const useRequest = (api: AxiosInstance, endpoint: string, search?: Search) => {
9
+ const [response, setResponse] = useState<Page>(initialPage)
10
+ const [error, setError] = useState<ErrorMessage[]>([initialErrorMessage])
11
+ const [loading, setLoading] = useState<boolean>(false)
12
+ const abortControllerRef = useRef<AbortController | null>(null)
13
+
14
+ const request = useCallback(async () => {
15
+ abortControllerRef.current?.abort()
16
+ const controller = new AbortController()
17
+ abortControllerRef.current = controller
18
+
19
+ try {
20
+ setLoading(true)
21
+ setError([initialErrorMessage])
22
+ const data = await FetchPage(api, endpoint, search, controller.signal)
23
+ setResponse(data)
24
+ } catch (requestError) {
25
+ setError([requestError as ErrorMessage])
26
+ } finally {
27
+ setLoading(false)
28
+ abortControllerRef.current = null
29
+ }
30
+ }, [endpoint, search])
31
+
32
+ useEffect(() => {
33
+ request()
34
+ return () => abortControllerRef.current?.abort()
35
+ }, [request])
36
+
37
+ return { response, error, loading, request }
38
+ }
@@ -0,0 +1,20 @@
1
+ import { useContext } from 'react'
2
+ import { useLocation, Navigate, Outlet } from 'react-router-dom'
3
+ import { AuthContext } from './useProvider'
4
+
5
+ export const useAuth = () => {
6
+ return useContext(AuthContext)
7
+ }
8
+
9
+ export const RequireAuth = ({ allowedRoles }: any) => {
10
+ const { role, accessToken } = useAuth()
11
+ const location = useLocation()
12
+
13
+ return (
14
+ role?.find((role: any) => allowedRoles?.includes(role))
15
+ ? <Outlet />
16
+ : accessToken
17
+ ? <Navigate to='/notAllowed' state={{ from: location }} replace />
18
+ : <Navigate to='/login' state={{ from: location }} replace />
19
+ )
20
+ }
@@ -0,0 +1,111 @@
1
+ import { AxiosInstance } from 'axios'
2
+ import { ErrorMessage } from '../component/errorMessage'
3
+ import { Search } from '../component/request'
4
+ import { removeToken, setToken } from './token'
5
+
6
+ // Respostas de informação (100-199),
7
+ // Respostas de sucesso (200-299),
8
+ // Redirecionamentos (300-399)
9
+ // Erros do cliente (400-499)
10
+ // Erros do servidor (500-599).
11
+
12
+ const addError = (error: any):ErrorMessage[] => {
13
+ let errorMessage: ErrorMessage[] = []
14
+ if (error.response.data.validationErrors !== undefined){
15
+ error.response.data?.validationErrors?.forEach((element: ErrorMessage) => {
16
+ errorMessage.push({ field: element.field, message: element.message })
17
+ })
18
+ } else {
19
+ errorMessage.push({ field: 'Error', message: 'Internal Error' })
20
+ }
21
+ return errorMessage
22
+ }
23
+
24
+ export const login = async<Auth,>(api: AxiosInstance, url: string, object: Auth) => {
25
+ return await api.post<Auth>(url, object)
26
+ .then(response => {
27
+ setToken(response.data)
28
+ return response.data
29
+ })
30
+ .catch(error => { return addError(error) })
31
+ }
32
+
33
+ export const reset = async<Auth,>(api: AxiosInstance, url: string, object: Auth) => {
34
+ return await api.put<Auth>(url, object)
35
+ .then(response => {
36
+ setToken(response.data)
37
+ return response.data
38
+ })
39
+ .catch(error => { return addError(error) })
40
+ }
41
+
42
+ export const logout = () => {
43
+ removeToken()
44
+ }
45
+
46
+ export const changePassword = async<User,>(api: AxiosInstance, data: User) => {
47
+ return await api.put<User>(`/user/changePassword`, data)
48
+ .then(response => {
49
+ return response.data
50
+ })
51
+ .catch(error => {
52
+ return addError(error) })
53
+ }
54
+
55
+ export const create = async<T,>(api: AxiosInstance, url: string, object: T) => {
56
+ return await api.post(`/${url}`, object)
57
+ .then(response => { return response.data })
58
+ .catch(error => { return addError(error) })
59
+ }
60
+
61
+ export const createAll = async<T,>(api: AxiosInstance, url: string, object: T[]) => {
62
+ return await api.post<T>(`/${url}/createAll`, object)
63
+ .then(response => { return response.data })
64
+ .catch(error => { return addError(error) })
65
+ }
66
+
67
+ export const retrieve = async<T,>(api: AxiosInstance, url: string, search?: Search, signal?: AbortSignal ) => {
68
+ if(search?.page === undefined && search?.size === undefined){
69
+ return await api.get<T>(`/${url}`)
70
+ .then(response => { return response.data })
71
+ .catch(error => { return addError(error) })
72
+ } else if (search?.sort?.order === undefined) {
73
+ return await api.get<T>(`/${url}?value=${search?.value}`, { params: { page: search?.page, size: search?.size }, signal } )
74
+ .then(response => { return response.data })
75
+ .catch(error => { return addError(error) })
76
+ } else {
77
+ return await api.get<T>(`/${url}?value=${search?.value}`, { params: { page: search?.page, size: search?.size, sort: `${search?.sort?.key},${search?.sort?.order}` }, signal } )
78
+ .then(response => { return response.data })
79
+ .catch(error => { return addError(error) })
80
+ }
81
+ }
82
+
83
+ export const update = async<T,>(api: AxiosInstance, url: string, object: T) => {
84
+ return await api.put<T>(`/${url}`, object)
85
+ .then(response => { return response.data })
86
+ .catch(error => { return addError(error) })
87
+ }
88
+
89
+ export const remove = async<T,>(api: AxiosInstance, url: string, id: string) => {
90
+ return await api.delete<T>(`/${url}/${id}`)
91
+ .then(response => { return response.data })
92
+ .catch(error => { return addError(error) })
93
+ }
94
+
95
+ export const removeComposite = async<T,>(api: AxiosInstance, url: string, object: Object, one: string, two: string, three: string, four: string) => {
96
+ if(three !== '' && four !== ''){
97
+ return await api.delete<T>(`/${url}`, object)
98
+ .then(response => { return response.data })
99
+ .catch(error => { return addError(error) })
100
+ } else {
101
+ return await api.delete<T>(`/${url}/${one}/${two}`, object)
102
+ .then(response => { return response.data })
103
+ .catch(error => { return addError(error) })
104
+ }
105
+ }
106
+
107
+ export const removeAll = async<T,>(api: AxiosInstance, url: string) => {
108
+ return await api.delete<T>(`/${url}`)
109
+ .then(response => { return response.data })
110
+ .catch(error => { return addError(error) });
111
+ }
@@ -0,0 +1,23 @@
1
+ import { AxiosInstance } from 'axios'
2
+ import { Page } from '../component/response'
3
+ import { Search } from '../component/request'
4
+
5
+ export const FetchPage = async (api: AxiosInstance, endpoint: string, search?: Search, signal?: AbortSignal): Promise<Page> => {
6
+ const uri = search?.value?.trim()
7
+ ? `/${endpoint}?value=${encodeURIComponent(search.value)}`
8
+ : `/${endpoint}`
9
+ const params: Record<string, unknown> = {
10
+ page: search?.page,
11
+ size: search?.size
12
+ }
13
+ if (search?.sort?.order && search?.sort?.key) {
14
+ params.sort = `${search.sort.key},${search.sort.order}`
15
+ }
16
+
17
+ const { data } = await api.get<Page>(uri, {
18
+ params: Object.keys(params).length > 0 ? params : undefined,
19
+ signal
20
+ })
21
+
22
+ return data
23
+ }
@@ -0,0 +1,94 @@
1
+ import { Auth, initialAuth } from '../component/auth'
2
+ import { Header, initialHeader, initialPayload, Payload } from '../component/token'
3
+
4
+ const isValidJSON = (json: string) => {
5
+ try {
6
+ JSON.parse(json)
7
+ return true
8
+ } catch {
9
+ return false
10
+ }
11
+ }
12
+
13
+ export const isValidToken = (): boolean => {
14
+ try {
15
+ const token = getToken()
16
+ if (!token?.accessToken) return false
17
+
18
+ const { exp } = getPayload()
19
+ if (typeof exp !== 'number') return false
20
+
21
+ return exp * 1000 > Date.now()
22
+ } catch {
23
+ return false
24
+ }
25
+ }
26
+
27
+ export const getToken = (): Auth => {
28
+ let token: string = `${localStorage.getItem(`token`)}`
29
+ return isValidJSON(token) ? JSON.parse(token) : initialAuth
30
+ }
31
+
32
+ export const setToken = (token: any): void => {
33
+ localStorage.setItem(`token`, JSON.stringify(token))
34
+ }
35
+
36
+ export const removeToken = () => {
37
+ localStorage.removeItem('token')
38
+ }
39
+
40
+ export const getPayload = (): Payload => {
41
+ try {
42
+ const token = getToken()
43
+ if (!token?.accessToken) return initialPayload;
44
+
45
+ const base64 = token.accessToken.split('.')[1]
46
+ .replace(/-/g, '+')
47
+ .replace(/_/g, '/')
48
+
49
+ const payload = decodeURIComponent(
50
+ atob(base64)
51
+ .split('')
52
+ .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
53
+ .join('')
54
+ )
55
+
56
+ return isValidJSON(payload) ? JSON.parse(payload) : initialPayload
57
+ } catch {
58
+ return initialPayload
59
+ }
60
+ }
61
+
62
+ export const decodeJwt = () => {
63
+ if (getToken() !== null) {
64
+ var base64Url = getToken().accessToken.split('.')[1];
65
+ var base64 = decodeURIComponent(atob(base64Url).split('').map((c) => {
66
+ return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
67
+ }).join(''))
68
+ return base64
69
+ } else {
70
+ return null
71
+ }
72
+ }
73
+
74
+ export const getHeader = (): Header => {
75
+ try {
76
+ const token = getToken()
77
+ if (!token?.accessToken) return initialHeader
78
+
79
+ const base64 = token.accessToken.split('.')[0]
80
+ .replace(/-/g, '+')
81
+ .replace(/_/g, '/')
82
+
83
+ const header = decodeURIComponent(
84
+ atob(base64)
85
+ .split('')
86
+ .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
87
+ .join('')
88
+ )
89
+
90
+ return isValidJSON(header) ? JSON.parse(header) : initialHeader
91
+ } catch {
92
+ return initialHeader
93
+ }
94
+ }