acinguiux-dnr-utils 0.0.4 → 0.0.5

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/README.md CHANGED
@@ -33,7 +33,7 @@ From the application layout it can be integrated like
33
33
  <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
34
34
  <link
35
35
  rel="stylesheet"
36
- href="https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:ital,wght@0,100..900,1,100..900&display=swap"
36
+ href="https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap"
37
37
  />
38
38
  </head>
39
39
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acinguiux-dnr-utils",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "dependencies": {
5
5
  "@auth/core": "^0.41.1",
6
6
  "next": "14.2.35"
@@ -3,7 +3,7 @@
3
3
  declare type RequestInit = any;
4
4
 
5
5
  import { auth } from "../authentication";
6
- import { logger } from "../instrumentation/node";
6
+ // import { logger } from "../instrumentation/node";
7
7
 
8
8
  export const authFetch = async (
9
9
  url: string,
@@ -49,17 +49,18 @@ export const authFetch = async (
49
49
  errorText = data || errorText;
50
50
  }
51
51
 
52
- logger.error(`API request failed for (${humanReadablePath})`, {
53
- path: pathname,
54
- params: searchParams.toString(),
55
- status: responseClone.status,
56
- statusText: responseClone.statusText,
57
- detail: errorText,
58
- user: {
59
- name: session?.user?.name || "Anonymous",
60
- email: session?.user?.email || "anonymous@shell.com",
61
- },
62
- });
52
+ // logger.error(`API request failed for (${humanReadablePath})`, {
53
+ // path: pathname,
54
+ // params: searchParams.toString(),
55
+ // status: responseClone.status,
56
+ // statusText: responseClone.statusText,
57
+ // detail: errorText,
58
+ // user: {
59
+ // name: session?.user?.name || "Anonymous",
60
+ // email: session?.user?.email || "anonymous@shell.com",
61
+ // },
62
+ // });
63
+ console.log('error', errorText);
63
64
 
64
65
  if (throwOnError) {
65
66
  throw new Error(errorText);
@@ -68,12 +69,13 @@ export const authFetch = async (
68
69
  }
69
70
  }
70
71
 
71
- logger.info(`API request succeeded for ${humanReadablePath}`, {
72
- path: pathname,
73
- params: searchParams.toString(),
74
- status: response.status,
75
- statusText: response.statusText,
76
- });
72
+ // logger.info(`API request succeeded for ${humanReadablePath}`, {
73
+ // path: pathname,
74
+ // params: searchParams.toString(),
75
+ // status: response.status,
76
+ // statusText: response.statusText,
77
+ // });
78
+ console.log('info')
77
79
 
78
80
  return response;
79
81
  };
@@ -1,383 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import * as auth_module from "../authentication";
3
- import * as logger_module from "../instrumentation/node";
4
- import { authFetch } from "./auth-fetch";
5
-
6
- vi.mock("../authentication", () => ({
7
- auth: vi.fn(() => ({
8
- access_token: "test-token",
9
- user: { name: "Test User", email: "test@example.com" },
10
- })),
11
- }));
12
-
13
- vi.mock("../instrumentation/node", () => ({
14
- logger: {
15
- error: vi.fn(),
16
- info: vi.fn(),
17
- },
18
- }));
19
-
20
- describe("authFetch", () => {
21
- const domain = "https://api.test.com";
22
- const path = "test/path";
23
- const queryParams = "key=value";
24
-
25
- beforeEach(() => {
26
- vi.restoreAllMocks();
27
- });
28
-
29
- const makeJsonResponse = (
30
- data: unknown,
31
- {
32
- ok = true,
33
- status = 200,
34
- statusText = "OK",
35
- contentType = "application/json",
36
- }: {
37
- ok?: boolean;
38
- status?: number;
39
- statusText?: string;
40
- contentType?: string;
41
- } = {},
42
- ) => {
43
- const response: any = {
44
- ok,
45
- json: () => Promise.resolve(data),
46
- headers: new Headers({ "content-type": contentType }),
47
- status,
48
- statusText,
49
- };
50
-
51
- if (!ok) {
52
- response.clone = () => ({
53
- json: () => Promise.resolve(data),
54
- status,
55
- statusText,
56
- });
57
- }
58
-
59
- return response;
60
- };
61
-
62
- const makeTextResponse = (
63
- text: string,
64
- {
65
- ok = true,
66
- status = 200,
67
- statusText = "OK",
68
- contentType = "text/plain",
69
- }: {
70
- ok?: boolean;
71
- status?: number;
72
- statusText?: string;
73
- contentType?: string;
74
- } = {},
75
- ) => {
76
- const response: any = {
77
- ok,
78
- text: () => Promise.resolve(text),
79
- headers: new Headers({ "content-type": contentType }),
80
- status,
81
- statusText,
82
- };
83
-
84
- if (!ok) {
85
- response.clone = () => ({
86
- text: () => Promise.resolve(text),
87
- status,
88
- statusText,
89
- });
90
- }
91
-
92
- return response;
93
- };
94
-
95
- const mockFetchResolved = (response: any) => {
96
- global.fetch = vi.fn().mockResolvedValue(response);
97
- };
98
-
99
- it("uses default requestOptions when no additional options are provided", async () => {
100
- mockFetchResolved(makeJsonResponse({}));
101
-
102
- await authFetch(`${domain}/${path}?${queryParams}`, {});
103
-
104
- expect(global.fetch).toHaveBeenCalledWith(
105
- `${domain}/${path}?${queryParams}`,
106
- expect.objectContaining({
107
- method: "GET",
108
- headers: expect.any(Headers),
109
- }),
110
- );
111
- });
112
-
113
- it("merges additional options into requestOptions", async () => {
114
- mockFetchResolved(makeJsonResponse({}));
115
-
116
- const additionalOptions = {
117
- method: "POST",
118
- body: JSON.stringify({ data: "test" }),
119
- };
120
-
121
- await authFetch(`${domain}/${path}?${queryParams}`, additionalOptions);
122
-
123
- expect(global.fetch).toHaveBeenCalledWith(
124
- `${domain}/${path}?${queryParams}`,
125
- expect.objectContaining({
126
- method: "POST",
127
- headers: expect.any(Headers),
128
- body: '{"data":"test"}',
129
- }),
130
- );
131
- });
132
-
133
- it("includes the Authorization header with the token", async () => {
134
- mockFetchResolved(makeJsonResponse({}));
135
-
136
- await authFetch(`${domain}/${path}`, {});
137
-
138
- const callArgs = (global.fetch as any).mock.calls[0];
139
- const headers = callArgs[1].headers as Headers;
140
-
141
- expect(headers.get("Authorization")).toBe("Bearer test-token");
142
- });
143
-
144
- it("logs success when response is ok with JSON content", async () => {
145
- mockFetchResolved(makeJsonResponse({ data: "success" }));
146
-
147
- await authFetch(`${domain}/${path}?${queryParams}`);
148
-
149
- const logger = logger_module.logger;
150
- expect(logger.info).toHaveBeenCalledWith(
151
- expect.stringContaining("API request succeeded"),
152
- expect.objectContaining({
153
- path: `/${path}`,
154
- status: 200,
155
- }),
156
- );
157
- });
158
-
159
- it("throws error when response is not ok with JSON error body", async () => {
160
- mockFetchResolved(
161
- makeJsonResponse(
162
- {
163
- context: {
164
- errors: [{ msg: "Invalid request" }, { msg: "Missing field" }],
165
- },
166
- },
167
- { ok: false, status: 400, statusText: "Bad Request" },
168
- ),
169
- );
170
-
171
- await expect(authFetch(`${domain}/${path}`)).rejects.toThrow("Invalid request | Missing field");
172
-
173
- const logger = logger_module.logger;
174
- expect(logger.error).toHaveBeenCalledWith(
175
- expect.stringContaining("API request failed"),
176
- expect.any(Object),
177
- );
178
- });
179
-
180
- it("throws error when response is not ok with text error body", async () => {
181
- mockFetchResolved(
182
- makeTextResponse("Error message", {
183
- ok: false,
184
- status: 500,
185
- statusText: "Internal Server Error",
186
- }),
187
- );
188
-
189
- await expect(authFetch(`${domain}/${path}`)).rejects.toThrow("Error message");
190
- });
191
-
192
- it("logs error with session data when request fails", async () => {
193
- mockFetchResolved(makeJsonResponse({}, { ok: false, status: 401, statusText: "Unauthorized" }));
194
-
195
- try {
196
- await authFetch(`${domain}/${path}`);
197
- } catch {
198
- // Expected error
199
- }
200
-
201
- const logger = logger_module.logger;
202
- expect(logger.error).toHaveBeenCalledWith(
203
- expect.any(String),
204
- expect.objectContaining({
205
- status: 401,
206
- user: expect.any(Object),
207
- }),
208
- );
209
- });
210
-
211
- it("logs error with anonymous user when session has no user", async () => {
212
- vi.mocked(auth_module.auth).mockResolvedValue({} as any);
213
-
214
- mockFetchResolved(makeJsonResponse({}, { ok: false, status: 401, statusText: "Unauthorized" }));
215
-
216
- try {
217
- await authFetch(`${domain}/${path}`);
218
- } catch {
219
- // Expected error
220
- }
221
-
222
- const logger = logger_module.logger;
223
- expect(logger.error).toHaveBeenCalledWith(
224
- expect.any(String),
225
- expect.objectContaining({
226
- user: expect.objectContaining({
227
- name: "Anonymous",
228
- email: "anonymous@shell.com",
229
- }),
230
- }),
231
- );
232
- });
233
-
234
- it("returns response object on successful fetch", async () => {
235
- const mockResponse = makeJsonResponse({ data: "test" });
236
-
237
- mockFetchResolved(mockResponse);
238
-
239
- const response = await authFetch(`${domain}/${path}`);
240
-
241
- expect(response).toBe(mockResponse);
242
- });
243
-
244
- it("sets Content-Type header to application/json", async () => {
245
- mockFetchResolved(makeJsonResponse({}));
246
-
247
- await authFetch(`${domain}/${path}`, {});
248
-
249
- const callArgs = (global.fetch as any).mock.calls[0];
250
- const headers = callArgs[1].headers as Headers;
251
-
252
- expect(headers.get("Content-Type")).toBe("application/json");
253
- });
254
-
255
- it("does not set Authorization header when session has no access_token", async () => {
256
- vi.mocked(auth_module.auth).mockResolvedValueOnce({
257
- user: { name: "Test User", email: "test@example.com" },
258
- } as any);
259
-
260
- mockFetchResolved(makeJsonResponse({}));
261
-
262
- await authFetch(`${domain}/${path}`, {});
263
-
264
- const callArgs = (global.fetch as any).mock.calls[0];
265
- const headers = callArgs[1].headers as Headers;
266
-
267
- expect(headers.get("Authorization")).toBeNull();
268
- });
269
-
270
- it("handles error response with no error context", async () => {
271
- mockFetchResolved(
272
- makeJsonResponse(
273
- { someOtherField: "value" },
274
- { ok: false, status: 400, statusText: "Bad Request" },
275
- ),
276
- );
277
-
278
- await expect(authFetch(`${domain}/${path}`)).rejects.toThrow(
279
- "Failed to read error response text.",
280
- );
281
- });
282
-
283
- it("handles error response with empty error array", async () => {
284
- mockFetchResolved(
285
- makeJsonResponse(
286
- { context: { errors: [] } },
287
- { ok: false, status: 400, statusText: "Bad Request" },
288
- ),
289
- );
290
-
291
- await expect(authFetch(`${domain}/${path}`)).rejects.toThrow(
292
- "Failed to read error response text.",
293
- );
294
- });
295
-
296
- it("handles error response with error messages from error array", async () => {
297
- mockFetchResolved(
298
- makeJsonResponse(
299
- {
300
- context: {
301
- errors: [{ msg: "Error 1" }, { msg: "Error 2" }, { other: "field" }],
302
- },
303
- },
304
- { ok: false, status: 400, statusText: "Bad Request" },
305
- ),
306
- );
307
-
308
- await expect(authFetch(`${domain}/${path}`)).rejects.toThrow(" | Error 1 | Error 2");
309
- });
310
-
311
- it("handles error response with non-JSON content type", async () => {
312
- mockFetchResolved(
313
- makeTextResponse("Text error response", {
314
- ok: false,
315
- status: 400,
316
- statusText: "Bad Request",
317
- }),
318
- );
319
-
320
- await expect(authFetch(`${domain}/${path}`)).rejects.toThrow("Text error response");
321
- });
322
-
323
- it("handles error response with empty text response", async () => {
324
- mockFetchResolved(
325
- makeTextResponse("", {
326
- ok: false,
327
- status: 400,
328
- statusText: "Bad Request",
329
- }),
330
- );
331
-
332
- await expect(authFetch(`${domain}/${path}`)).rejects.toThrow(
333
- "Failed to read error response text.",
334
- );
335
- });
336
-
337
- it("returns response when throwOnError is false and response is not ok", async () => {
338
- const mockResponse = makeJsonResponse(
339
- {
340
- context: {
341
- errors: [{ msg: "Error message" }],
342
- },
343
- },
344
- { ok: false, status: 400, statusText: "Bad Request" },
345
- );
346
-
347
- mockFetchResolved(mockResponse);
348
-
349
- const response = await authFetch(`${domain}/${path}`, {}, false);
350
-
351
- expect(response).toBe(mockResponse);
352
- expect(response.ok).toBe(false);
353
- // Verify the response body is still readable via clone
354
- const clonedBody = await response.clone().json();
355
- expect(clonedBody).toEqual({ context: { errors: [{ msg: "Error message" }] } });
356
- });
357
-
358
- it("logs error but does not throw when throwOnError is false", async () => {
359
- const mockResponse = makeJsonResponse(
360
- {
361
- context: {
362
- errors: [{ msg: "Test error" }],
363
- },
364
- },
365
- { ok: false, status: 400, statusText: "Bad Request" },
366
- );
367
-
368
- mockFetchResolved(mockResponse);
369
-
370
- const response = await authFetch(`${domain}/${path}`, {}, false);
371
-
372
- expect(response.ok).toBe(false);
373
-
374
- const logger = logger_module.logger;
375
- expect(logger.error).toHaveBeenCalledWith(
376
- expect.stringContaining("API request failed"),
377
- expect.any(Object),
378
- );
379
- // Verify the response body is still readable via clone
380
- const clonedBody = await response.clone().json();
381
- expect(clonedBody).toEqual({ context: { errors: [{ msg: "Test error" }] } });
382
- });
383
- });