@murabei-data-science/pumpwood-services 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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +504 -0
  3. package/dist/example-usage.d.ts +8 -0
  4. package/dist/example-usage.d.ts.map +1 -0
  5. package/dist/example-usage.js +156 -0
  6. package/dist/example-usage.js.map +1 -0
  7. package/dist/index.d.ts +22 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +43 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/jest.setup.d.ts +2 -0
  12. package/dist/jest.setup.d.ts.map +1 -0
  13. package/dist/jest.setup.js +8 -0
  14. package/dist/jest.setup.js.map +1 -0
  15. package/dist/src/core/api-service.d.ts +58 -0
  16. package/dist/src/core/api-service.d.ts.map +1 -0
  17. package/dist/src/core/api-service.js +192 -0
  18. package/dist/src/core/api-service.js.map +1 -0
  19. package/dist/src/core/pumpwood-client.d.ts +46 -0
  20. package/dist/src/core/pumpwood-client.d.ts.map +1 -0
  21. package/dist/src/core/pumpwood-client.js +110 -0
  22. package/dist/src/core/pumpwood-client.js.map +1 -0
  23. package/dist/src/core/safe-await.d.ts +20 -0
  24. package/dist/src/core/safe-await.d.ts.map +1 -0
  25. package/dist/src/core/safe-await.js +31 -0
  26. package/dist/src/core/safe-await.js.map +1 -0
  27. package/dist/src/services/delete.d.ts +17 -0
  28. package/dist/src/services/delete.d.ts.map +1 -0
  29. package/dist/src/services/delete.js +28 -0
  30. package/dist/src/services/delete.js.map +1 -0
  31. package/dist/src/services/execute-action-file.d.ts +43 -0
  32. package/dist/src/services/execute-action-file.d.ts.map +1 -0
  33. package/dist/src/services/execute-action-file.js +50 -0
  34. package/dist/src/services/execute-action-file.js.map +1 -0
  35. package/dist/src/services/execute-action.d.ts +47 -0
  36. package/dist/src/services/execute-action.d.ts.map +1 -0
  37. package/dist/src/services/execute-action.js +54 -0
  38. package/dist/src/services/execute-action.js.map +1 -0
  39. package/dist/src/services/execute-static-action-file.d.ts +46 -0
  40. package/dist/src/services/execute-static-action-file.d.ts.map +1 -0
  41. package/dist/src/services/execute-static-action-file.js +55 -0
  42. package/dist/src/services/execute-static-action-file.js.map +1 -0
  43. package/dist/src/services/execute-static-action.d.ts +33 -0
  44. package/dist/src/services/execute-static-action.d.ts.map +1 -0
  45. package/dist/src/services/execute-static-action.js +44 -0
  46. package/dist/src/services/execute-static-action.js.map +1 -0
  47. package/dist/src/services/get-sso-token.d.ts +19 -0
  48. package/dist/src/services/get-sso-token.d.ts.map +1 -0
  49. package/dist/src/services/get-sso-token.js +58 -0
  50. package/dist/src/services/get-sso-token.js.map +1 -0
  51. package/dist/src/services/list-without-pag.d.ts +23 -0
  52. package/dist/src/services/list-without-pag.d.ts.map +1 -0
  53. package/dist/src/services/list-without-pag.js +37 -0
  54. package/dist/src/services/list-without-pag.js.map +1 -0
  55. package/dist/src/services/list.d.ts +18 -0
  56. package/dist/src/services/list.d.ts.map +1 -0
  57. package/dist/src/services/list.js +32 -0
  58. package/dist/src/services/list.js.map +1 -0
  59. package/dist/src/services/login-sso.d.ts +16 -0
  60. package/dist/src/services/login-sso.d.ts.map +1 -0
  61. package/dist/src/services/login-sso.js +50 -0
  62. package/dist/src/services/login-sso.js.map +1 -0
  63. package/dist/src/services/login.d.ts +21 -0
  64. package/dist/src/services/login.d.ts.map +1 -0
  65. package/dist/src/services/login.js +54 -0
  66. package/dist/src/services/login.js.map +1 -0
  67. package/dist/src/services/retrieve-file.d.ts +25 -0
  68. package/dist/src/services/retrieve-file.d.ts.map +1 -0
  69. package/dist/src/services/retrieve-file.js +36 -0
  70. package/dist/src/services/retrieve-file.js.map +1 -0
  71. package/dist/src/services/retrieve-options.d.ts +18 -0
  72. package/dist/src/services/retrieve-options.d.ts.map +1 -0
  73. package/dist/src/services/retrieve-options.js +29 -0
  74. package/dist/src/services/retrieve-options.js.map +1 -0
  75. package/dist/src/services/retrieve.d.ts +13 -0
  76. package/dist/src/services/retrieve.d.ts.map +1 -0
  77. package/dist/src/services/retrieve.js +26 -0
  78. package/dist/src/services/retrieve.js.map +1 -0
  79. package/dist/src/services/save.d.ts +18 -0
  80. package/dist/src/services/save.d.ts.map +1 -0
  81. package/dist/src/services/save.js +31 -0
  82. package/dist/src/services/save.js.map +1 -0
  83. package/dist/src/services/upload.d.ts +25 -0
  84. package/dist/src/services/upload.d.ts.map +1 -0
  85. package/dist/src/services/upload.js +41 -0
  86. package/dist/src/services/upload.js.map +1 -0
  87. package/dist/src/types/error.d.ts +13 -0
  88. package/dist/src/types/error.d.ts.map +1 -0
  89. package/dist/src/types/error.js +53 -0
  90. package/dist/src/types/error.js.map +1 -0
  91. package/dist/src/types/http.d.ts +42 -0
  92. package/dist/src/types/http.d.ts.map +1 -0
  93. package/dist/src/types/http.js +3 -0
  94. package/dist/src/types/http.js.map +1 -0
  95. package/package.json +34 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Murabei
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,504 @@
1
+ # pumpwood-services
2
+
3
+ Biblioteca TypeScript para conectar e interagir com uma API Pumpwood. Fornece um cliente de alto nível (`PumpwoodClient`) e serviços individuais para operações CRUD, uploads, downloads e execução de actions.
4
+
5
+ ## Instalação
6
+
7
+ ```bash
8
+ npm install @murabei-data-science/pumpwood-services
9
+ ```
10
+
11
+ ## Início rápido
12
+
13
+ ### Client-side (browser)
14
+
15
+ Crie o cliente **uma vez** como singleton e importe onde precisar:
16
+
17
+ ```typescript
18
+ // src/lib/pumpwood.ts
19
+ import { PumpwoodClient } from "@murabei-data-science/pumpwood-services";
20
+
21
+ export const pumpwood = new PumpwoodClient({
22
+ baseUrl: "https://api.seuapp.com/rest",
23
+ token: () => localStorage.getItem("auth_token") ?? "",
24
+ // ↑ factory: reavaliada a cada request
25
+ });
26
+ ```
27
+
28
+ ### Server-side (Next.js Server Actions)
29
+
30
+ ```typescript
31
+ // src/lib/pumpwood.server.ts
32
+ import { PumpwoodClient } from "@murabei-data-science/pumpwood-services";
33
+ import { cookies } from "next/headers";
34
+
35
+ async function getToken(): Promise<string> {
36
+ return (await cookies()).get("auth_token")?.value ?? "";
37
+ }
38
+
39
+ export const pumpwood = new PumpwoodClient({
40
+ baseUrl: process.env.NEXT_PUBLIC_APP_API_URL!,
41
+ token: getToken,
42
+ });
43
+ ```
44
+
45
+ ### Uso direto na page / server action
46
+
47
+ ```typescript
48
+ import { pumpwood } from "@/lib/pumpwood.server";
49
+
50
+ export async function fetchVariable(id: string) {
51
+ const [data, error] = await pumpwood.retrieve<IMyModel>(
52
+ "mymodel",
53
+ Number.parseInt(id, 10),
54
+ { foreign_key_fields: true, related_fields: true },
55
+ );
56
+ if (error) throw new Error(error.message);
57
+ if (!data) throw new Error("Nenhum dado retornado");
58
+ return data;
59
+ }
60
+ ```
61
+
62
+ ---
63
+
64
+ ## `PumpwoodClient` — referência completa
65
+
66
+ ### `list`
67
+
68
+ ```typescript
69
+ pumpwood.list<T>(modelClass, body?, queryParams?)
70
+ ```
71
+
72
+ `POST /{modelClass}/list/` — listagem paginada com filtros.
73
+
74
+ ```typescript
75
+ const [areas, error] = await pumpwood.list<GeoArea[]>("descriptiongeoarea", {
76
+ filter_dict: { is_active: true },
77
+ order_by: ["-created_at"],
78
+ limit: 20,
79
+ offset: 0,
80
+ });
81
+ if (error) throw new Error(error.message);
82
+ ```
83
+
84
+ ---
85
+
86
+ ### `listWithoutPag`
87
+
88
+ ```typescript
89
+ pumpwood.listWithoutPag<T>(modelClass, body?, queryParams?)
90
+ ```
91
+
92
+ `POST /{modelClass}/list-without-pag/` — retorna **todos** os resultados sem paginação. Use para datasets pequenos (lookups, combos, versões).
93
+
94
+ ```typescript
95
+ const [allAreas, error] = await pumpwood.listWithoutPag<GeoArea[]>(
96
+ "descriptiongeoarea",
97
+ {
98
+ filter_dict: { is_active: true },
99
+ fields: ["pk", "name"],
100
+ order_by: ["name"],
101
+ },
102
+ );
103
+ if (error) throw new Error(error.message);
104
+ ```
105
+
106
+ ---
107
+
108
+ ### `retrieve`
109
+
110
+ ```typescript
111
+ pumpwood.retrieve<T>(modelClass, pk, options?)
112
+ ```
113
+
114
+ `GET /{modelClass}/retrieve/{pk}/` — busca um registro por pk.
115
+
116
+ `options` aceita booleans diretamente (convertidos para query params internamente):
117
+
118
+ ```typescript
119
+ const [area, error] = await pumpwood.retrieve<GeoArea>(
120
+ "descriptiongeoarea",
121
+ 1,
122
+ { foreign_key_fields: true, related_fields: true },
123
+ );
124
+ if (error) throw new Error(error.message);
125
+ ```
126
+
127
+ ---
128
+
129
+ ### `retrieveOptions`
130
+
131
+ ```typescript
132
+ pumpwood.retrieveOptions<T>(modelClass, body?)
133
+ ```
134
+
135
+ `POST /{modelClass}/retrieve-options/` — busca definições de campos, choices e regras de validação do modelo.
136
+
137
+ ```typescript
138
+ const [options, error] = await pumpwood.retrieveOptions("descriptiongeoarea");
139
+ if (error) throw new Error(error.message);
140
+ ```
141
+
142
+ ---
143
+
144
+ ### `save`
145
+
146
+ ```typescript
147
+ pumpwood.save<T>(modelClass, body, options?)
148
+ ```
149
+
150
+ `POST /{modelClass}/save/` — cria se `pk=null`, atualiza se `pk` existe.
151
+
152
+ ```typescript
153
+ const [saved, error] = await pumpwood.save<GeoArea>(
154
+ "descriptiongeoarea",
155
+ { pk: null, name: "Nova Área" },
156
+ { foreign_key_fields: true },
157
+ );
158
+ if (error) throw new Error(error.message);
159
+ ```
160
+
161
+ ---
162
+
163
+ ### `delete`
164
+
165
+ ```typescript
166
+ pumpwood.delete<T>(modelClass, pk);
167
+ ```
168
+
169
+ `DELETE /{modelClass}/delete/{pk}/`
170
+
171
+ ```typescript
172
+ const [, error] = await pumpwood.delete("descriptiongeoarea", 1);
173
+ if (error) throw new Error(error.message);
174
+ ```
175
+
176
+ ---
177
+
178
+ ### `uploadFile`
179
+
180
+ ```typescript
181
+ pumpwood.uploadFile<T>(modelClass, file, jsonData, queryParams?)
182
+ ```
183
+
184
+ `POST /{modelClass}/save/` via `multipart/form-data`. O arquivo é enviado como `"file"` e os dados JSON como `"__json__"`.
185
+
186
+ ```typescript
187
+ const file = new File(["conteúdo"], "data.csv", { type: "text/csv" });
188
+ const [result, error] = await pumpwood.uploadFile("documents", file, {
189
+ origin: "USER_UPLOAD",
190
+ format_type: "MELTED",
191
+ });
192
+ if (error) throw new Error(error.message);
193
+ ```
194
+
195
+ ---
196
+
197
+ ### `retrieveFile`
198
+
199
+ ```typescript
200
+ pumpwood.retrieveFile(modelClass, pk, fileField?)
201
+ ```
202
+
203
+ `GET /{modelClass}/retrieve-file/{pk}/?file-field={fileField}` — retorna `IFileData` (`{ blob, contentType }`).
204
+
205
+ ⚠️ **Sempre use `try/finally` para revogar o URL e evitar memory leak:**
206
+
207
+ ```typescript
208
+ const [fileData, error] = await pumpwood.retrieveFile("documents", 42, "file");
209
+ if (error) throw new Error(error.message);
210
+
211
+ const url = URL.createObjectURL(fileData!.blob);
212
+ try {
213
+ window.open(url);
214
+ } finally {
215
+ URL.revokeObjectURL(url);
216
+ }
217
+ ```
218
+
219
+ ---
220
+
221
+ ### `executeAction`
222
+
223
+ ```typescript
224
+ pumpwood.executeAction<T>({ modelClass, pk, actionName, parameters?, queryParams? })
225
+ ```
226
+
227
+ `POST /{modelClass}/actions/{actionName}/{pk}/` — executa uma action em uma instância.
228
+
229
+ ```typescript
230
+ const [result, error] = await pumpwood.executeAction({
231
+ modelClass: "MaterialApprovalActivity",
232
+ pk: 123,
233
+ actionName: "review",
234
+ parameters: { new_status: "approved" },
235
+ });
236
+ if (error) throw new Error(error.message);
237
+ ```
238
+
239
+ ---
240
+
241
+ ### `executeStaticAction`
242
+
243
+ ```typescript
244
+ pumpwood.executeStaticAction<T>({ modelClass, actionName, parameters?, queryParams? })
245
+ ```
246
+
247
+ Wrapper de `executeAction` com `pk=0`. Para actions de classe que não operam em instância específica.
248
+
249
+ ```typescript
250
+ const [stats, error] = await pumpwood.executeStaticAction({
251
+ modelClass: "MaterialApprovalActivity",
252
+ actionName: "get_statistics",
253
+ parameters: { year: 2024 },
254
+ });
255
+ if (error) throw new Error(error.message);
256
+ ```
257
+
258
+ ---
259
+
260
+ ### `executeActionFile`
261
+
262
+ ```typescript
263
+ pumpwood.executeActionFile({ modelClass, pk, actionName, parameters?, queryParams? })
264
+ ```
265
+
266
+ `POST /{modelClass}/actions/{actionName}/{pk}/` — action que retorna arquivo binário (Excel, PDF, CSV). Retorna `IFileData`.
267
+
268
+ ⚠️ **Sempre revogue o URL após o download:**
269
+
270
+ ```typescript
271
+ const [fileData, error] = await pumpwood.executeActionFile({
272
+ modelClass: "Report",
273
+ pk: 123,
274
+ actionName: "export_excel",
275
+ });
276
+ if (error) throw new Error(error.message);
277
+
278
+ const url = URL.createObjectURL(fileData!.blob);
279
+ const a = document.createElement("a");
280
+ a.href = url;
281
+ a.download = "report.xlsx";
282
+ document.body.appendChild(a);
283
+ try {
284
+ a.click();
285
+ } finally {
286
+ document.body.removeChild(a);
287
+ URL.revokeObjectURL(url);
288
+ }
289
+ ```
290
+
291
+ ---
292
+
293
+ ### `executeStaticActionFile`
294
+
295
+ ```typescript
296
+ pumpwood.executeStaticActionFile({ modelClass, actionName, parameters?, queryParams? })
297
+ ```
298
+
299
+ Wrapper de `executeActionFile` com `pk=0`. Para exports/geração de arquivos sem instância.
300
+
301
+ ```typescript
302
+ const [fileData, error] = await pumpwood.executeStaticActionFile({
303
+ modelClass: "DataExport",
304
+ actionName: "generate_report",
305
+ parameters: { year: 2024, format: "xlsx" },
306
+ });
307
+ if (error) throw new Error(error.message);
308
+
309
+ const url = URL.createObjectURL(fileData!.blob);
310
+ try {
311
+ const a = document.createElement("a");
312
+ a.href = url;
313
+ a.download = "export.xlsx";
314
+ a.click();
315
+ } finally {
316
+ URL.revokeObjectURL(url);
317
+ }
318
+ ```
319
+
320
+ ---
321
+
322
+ ### `loginWithCredentials`
323
+
324
+ ```typescript
325
+ pumpwood.loginWithCredentials({ username, password });
326
+ ```
327
+
328
+ `POST /registration/login/` — autentica com username e password, retorna o token.
329
+
330
+ ```typescript
331
+ const [result, error] = await pumpwood.loginWithCredentials({
332
+ username: "john",
333
+ password: "secret",
334
+ });
335
+ if (error) throw new Error(error.message);
336
+
337
+ // Consumidor decide onde guardar o token (cookie, localStorage, etc.)
338
+ setCookie("PumpwoodAuthorization", result.token);
339
+ ```
340
+
341
+ ---
342
+
343
+ ### `loginWithSSO`
344
+
345
+ ```typescript
346
+ pumpwood.loginWithSSO(email);
347
+ ```
348
+
349
+ `POST /registration/oauth2-login/` — inicia o fluxo SSO OAuth2, retorna a URL de redirecionamento.
350
+
351
+ ```typescript
352
+ const [result, error] = await pumpwood.loginWithSSO("user@example.com");
353
+ if (error) throw new Error(error.message);
354
+
355
+ // Redireciona para o provider OAuth2
356
+ window.location.href = result.redirect_url;
357
+ ```
358
+
359
+ ---
360
+
361
+ ### `getSSOToken`
362
+
363
+ ```typescript
364
+ pumpwood.getSSOToken(url);
365
+ ```
366
+
367
+ Troca a URL de callback SSO (após redirect do provider) pelo token e dados do usuário.
368
+
369
+ ```typescript
370
+ // Chamado após o provider redirecionar de volta
371
+ const callbackUrl = `${baseUrl}/sso/callback/?code=xyz&state=abc`;
372
+ const [result, error] = await pumpwood.getSSOToken(callbackUrl);
373
+ if (error) throw new Error(error.message);
374
+
375
+ setCookie("PumpwoodAuthorization", result.token);
376
+ setCookie("user", JSON.stringify(result.user)); // { email, username }
377
+ ```
378
+
379
+ ---
380
+
381
+ ## Serviços de baixo nível
382
+
383
+ Para quem precisa de controle direto, todos os serviços também são exportados individualmente e recebem um `ApiService` explícito:
384
+
385
+ ```typescript
386
+ import { ApiService, ListService, RetrieveService } from "@murabei-data-science/pumpwood-services";
387
+
388
+ const api = new ApiService({ baseUrl: "...", token: "..." });
389
+
390
+ const [items, error] = await ListService<Item[]>(api, "mymodel", {
391
+ filter_dict: {},
392
+ });
393
+ ```
394
+
395
+ Serviços disponíveis: `ListService`, `ListWithoutPagService`, `RetrieveService`, `RetrieveOptionsService`, `RetrieveFileService`, `SaveService`, `DeleteService`, `UploadFileService`, `ExecuteActionService`, `ExecuteStaticActionService`, `ExecuteActionFileService`, `LoginService`, `LoginSSOService`, `GetSSOTokenService`.
396
+
397
+ ---
398
+
399
+ ## Erros de autenticação (401)
400
+
401
+ Quando o token expira ou é inválido, a API retorna **401**. Configure `onUnauthorized` **uma vez** no `PumpwoodClient` para limpar a sessão e redirecionar ao login:
402
+
403
+ ### Server-side (Next.js Server Actions)
404
+
405
+ ```typescript
406
+ // src/lib/pumpwood.server.ts
407
+ import { PumpwoodClient } from "@murabei-data-science/pumpwood-services";
408
+ import { cookies } from "next/headers";
409
+ import { redirect } from "next/navigation";
410
+
411
+ async function getToken() {
412
+ return (await cookies()).get("PumpwoodAuthorization")?.value ?? "";
413
+ }
414
+
415
+ async function logout() {
416
+ (await cookies()).delete("PumpwoodAuthorization");
417
+ (await cookies()).delete("user");
418
+ redirect("/login?session-expired=true");
419
+ }
420
+
421
+ export const pumpwood = new PumpwoodClient({
422
+ baseUrl: process.env.API_URL!,
423
+ token: getToken,
424
+ onUnauthorized: logout,
425
+ });
426
+ ```
427
+
428
+ ### Client-side (browser)
429
+
430
+ ```typescript
431
+ export const pumpwood = new PumpwoodClient({
432
+ baseUrl: process.env.NEXT_PUBLIC_API_URL!,
433
+ token: () => localStorage.getItem("auth_token") ?? "",
434
+ onUnauthorized: () => {
435
+ localStorage.removeItem("auth_token");
436
+ window.location.href = "/login?session-expired=true";
437
+ },
438
+ });
439
+ ```
440
+
441
+ Uso normal — a lib chama `onUnauthorized` automaticamente antes de retornar o erro:
442
+
443
+ ```typescript
444
+ const [data, error] = await pumpwood.list("mymodel", filter);
445
+ if (error) throw new Error(error.message);
446
+ ```
447
+
448
+ ### Uso low-level (`ApiService` direto)
449
+
450
+ ```typescript
451
+ const api = new ApiService({
452
+ baseUrl: "...",
453
+ token: "...",
454
+ onUnauthorized: logout,
455
+ });
456
+
457
+ // ou, sem callback:
458
+ import { isUnauthorizedError } from "@murabei-data-science/pumpwood-services";
459
+
460
+ if (isUnauthorizedError(error)) await logout();
461
+ ```
462
+
463
+ O campo `error.status` (401) e o helper `isUnauthorizedError(error)` também estão disponíveis no `IErrorDict` retornado pelos serviços.
464
+
465
+ > Endpoints de login (`loginWithCredentials`, `loginWithSSO`, `getSSOToken`) **não** disparam `onUnauthorized` — 401 nesses casos significa credenciais inválidas, não sessão expirada.
466
+
467
+ ---
468
+
469
+ ## Tipos exportados
470
+
471
+ | Tipo / Interface | Descrição |
472
+ | ----------------------- | -------------------------------------------------------------------------------- |
473
+ | `IErrorDict` | Formato padronizado de erro: `{ message, type, payload, status?, ... }` |
474
+ | `UnauthorizedHandler` | Callback `() => void \| Promise<void>` para sessão expirada (401) |
475
+ | `IFileData` | Dados de arquivo: `{ blob: Blob, contentType: string }` |
476
+ | `IRetrieveOptions` | Opções para `retrieve` e `save`: `{ foreign_key_fields?, related_fields?, ... }` |
477
+ | `ISaveOptions` | Alias tipado para opções de `save` (mesma forma que `IRetrieveOptions`) |
478
+ | `IPumpwoodClientConfig` | Config do `PumpwoodClient`: `{ baseUrl, token, onUnauthorized? }` |
479
+ | `TokenProvider` | `string` ou `() => string \| Promise<string>` |
480
+ | `ApiServiceConfig` | Config do `ApiService`: `{ baseUrl, token, onUnauthorized? }` |
481
+ | `HttpMethod` | `"GET" \| "POST" \| "PUT" \| "DELETE"` |
482
+ | `ILoginResult` | Resultado de `loginWithCredentials`: `{ token: string }` |
483
+ | `ILoginSSOResult` | Resultado de `loginWithSSO`: `{ redirect_url: string }` |
484
+ | `IGetSSOTokenUser` | Dados do usuário SSO: `{ email: string, username: string }` |
485
+ | `IGetSSOTokenResult` | Resultado de `getSSOToken`: `{ token: string, user: IGetSSOTokenUser }` |
486
+
487
+ ---
488
+
489
+ ## Memory leak — downloads com Blob URL
490
+
491
+ Toda operação que retorna `IFileData` (Blob) requer que o URL criado por `URL.createObjectURL` seja revogado após o uso. Sem isso, o browser mantém a referência ao Blob em memória até o fechamento da aba.
492
+
493
+ **Padrão correto:**
494
+
495
+ ```typescript
496
+ const url = URL.createObjectURL(blob);
497
+ try {
498
+ // usa o url
499
+ } finally {
500
+ URL.revokeObjectURL(url); // sempre executado, mesmo em caso de erro
501
+ }
502
+ ```
503
+
504
+ Para detalhes e o caso especial de Next.js Server Actions (serialização Blob → `number[]`), veja [`docs/adr-execute-action-file.md`](./docs/adr-execute-action-file.md).
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Exemplos de uso do PumpwoodClient.
3
+ *
4
+ * Em projetos externos: import { PumpwoodClient } from "pumpwood-services";
5
+ */
6
+ import { PumpwoodClient } from "./index.js";
7
+ export declare const pumpwood: PumpwoodClient;
8
+ //# sourceMappingURL=example-usage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"example-usage.d.ts","sourceRoot":"","sources":["../example-usage.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAQ5C,eAAO,MAAM,QAAQ,gBAInB,CAAC"}
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pumpwood = void 0;
4
+ /**
5
+ * Exemplos de uso do PumpwoodClient.
6
+ *
7
+ * Em projetos externos: import { PumpwoodClient } from "pumpwood-services";
8
+ */
9
+ const index_js_1 = require("./index.js");
10
+ // =============================================================================
11
+ // CONFIGURAÇÃO — crie o cliente UMA VEZ como singleton
12
+ //
13
+ // CLIENT-SIDE (browser) — Arquivo: src/lib/pumpwood.ts
14
+ // =============================================================================
15
+ exports.pumpwood = new index_js_1.PumpwoodClient({
16
+ baseUrl: "http://localhost:8080/rest",
17
+ token: () => localStorage.getItem("auth_token") ?? "",
18
+ // ↑ factory: reavaliada a cada request, sem precisar recriar o cliente
19
+ });
20
+ async function referenceExamples() {
21
+ // --- LIST ---
22
+ // Listagem paginada com filtros
23
+ const [areas, listErr] = await exports.pumpwood.list("descriptiongeoarea", {
24
+ filter_dict: { is_active: true },
25
+ order_by: ["-created_at"],
26
+ limit: 20,
27
+ offset: 0,
28
+ });
29
+ if (listErr)
30
+ throw new Error(listErr.message);
31
+ // Listagem SEM paginação — para datasets pequenos (lookups, combos, etc.)
32
+ const [allAreas, listNoPagErr] = await exports.pumpwood.listWithoutPag("descriptiongeoarea", {
33
+ filter_dict: { is_active: true },
34
+ fields: ["pk", "name"],
35
+ order_by: ["name"],
36
+ });
37
+ if (listNoPagErr)
38
+ throw new Error(listNoPagErr.message);
39
+ // --- RETRIEVE ---
40
+ // Busca simples
41
+ const [area, retrieveErr] = await exports.pumpwood.retrieve("descriptiongeoarea", 1);
42
+ if (retrieveErr)
43
+ throw new Error(retrieveErr.message);
44
+ // Busca com relações expandidas — opções tipadas com boolean
45
+ const [areaFull, retrieveFullErr] = await exports.pumpwood.retrieve("descriptiongeoarea", 1, { foreign_key_fields: true, related_fields: true });
46
+ if (retrieveFullErr)
47
+ throw new Error(retrieveFullErr.message);
48
+ // Opções do modelo (field definitions, choices, validation rules)
49
+ const [options, optionsErr] = await exports.pumpwood.retrieveOptions("descriptiongeoarea");
50
+ if (optionsErr)
51
+ throw new Error(optionsErr.message);
52
+ // --- SAVE ---
53
+ // Cria se pk=null, atualiza se pk existe
54
+ const [saved, saveErr] = await exports.pumpwood.save("descriptiongeoarea", {
55
+ pk: null,
56
+ name: "Nova Área",
57
+ });
58
+ if (saveErr)
59
+ throw new Error(saveErr.message);
60
+ // Save retornando relações expandidas
61
+ const [savedFull, saveFullErr] = await exports.pumpwood.save("descriptiongeoarea", { pk: 1, name: "Área Atualizada" }, { foreign_key_fields: true });
62
+ if (saveFullErr)
63
+ throw new Error(saveFullErr.message);
64
+ // --- DELETE ---
65
+ const [, deleteErr] = await exports.pumpwood.delete("descriptiongeoarea", 1);
66
+ if (deleteErr)
67
+ throw new Error(deleteErr.message);
68
+ // --- ACTIONS ---
69
+ // Action em instância (com pk)
70
+ const [, actionErr] = await exports.pumpwood.executeAction({
71
+ modelClass: "MaterialApprovalActivity",
72
+ pk: 123,
73
+ actionName: "review",
74
+ parameters: { new_status: "approved" },
75
+ });
76
+ if (actionErr)
77
+ throw new Error(actionErr.message);
78
+ // Static action (sem instância — pk=0 internamente)
79
+ const [stats, staticActionErr] = await exports.pumpwood.executeStaticAction({
80
+ modelClass: "MaterialApprovalActivity",
81
+ actionName: "get_statistics",
82
+ parameters: { year: 2024 },
83
+ });
84
+ if (staticActionErr)
85
+ throw new Error(staticActionErr.message);
86
+ // --- UPLOAD DE ARQUIVO ---
87
+ const file = new File(["conteúdo"], "data.csv", { type: "text/csv" });
88
+ const [, uploadErr] = await exports.pumpwood.uploadFile("documents", file, { origin: "USER_UPLOAD", format_type: "MELTED" });
89
+ if (uploadErr)
90
+ throw new Error(uploadErr.message);
91
+ // --- DOWNLOAD DE ARQUIVO (retrieve-file) ---
92
+ // ⚠️ Use try/finally para garantir que o URL seja sempre revogado
93
+ const [fileData, fileErr] = await exports.pumpwood.retrieveFile("documents", 42, "file");
94
+ if (fileErr)
95
+ throw new Error(fileErr.message);
96
+ {
97
+ const url = URL.createObjectURL(fileData.blob);
98
+ try {
99
+ window.open(url);
100
+ }
101
+ finally {
102
+ URL.revokeObjectURL(url);
103
+ }
104
+ }
105
+ // --- ACTION QUE RETORNA ARQUIVO (ex: export Excel/PDF) ---
106
+ // Instância com pk
107
+ const [reportFile, reportErr] = await exports.pumpwood.executeActionFile({
108
+ modelClass: "Report",
109
+ pk: 123,
110
+ actionName: "export_excel",
111
+ parameters: { include_charts: true },
112
+ });
113
+ if (reportErr)
114
+ throw new Error(reportErr.message);
115
+ {
116
+ const url = URL.createObjectURL(reportFile.blob);
117
+ try {
118
+ const a = document.createElement("a");
119
+ a.href = url;
120
+ a.download = "report.xlsx";
121
+ a.click();
122
+ }
123
+ finally {
124
+ URL.revokeObjectURL(url); // sempre revogue para evitar memory leak
125
+ }
126
+ }
127
+ // Static action que retorna arquivo (sem instância)
128
+ const [exportFile, exportErr] = await exports.pumpwood.executeStaticActionFile({
129
+ modelClass: "DataExport",
130
+ actionName: "generate_report",
131
+ parameters: { year: 2024, format: "xlsx" },
132
+ });
133
+ if (exportErr)
134
+ throw new Error(exportErr.message);
135
+ {
136
+ const url = URL.createObjectURL(exportFile.blob);
137
+ try {
138
+ const a = document.createElement("a");
139
+ a.href = url;
140
+ a.download = "export.xlsx";
141
+ a.click();
142
+ }
143
+ finally {
144
+ URL.revokeObjectURL(url);
145
+ }
146
+ }
147
+ void areas;
148
+ void allAreas;
149
+ void area;
150
+ void areaFull;
151
+ void options;
152
+ void saved;
153
+ void savedFull;
154
+ void stats;
155
+ }
156
+ //# sourceMappingURL=example-usage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"example-usage.js","sourceRoot":"","sources":["../example-usage.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,y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