@arkyn/server 3.0.1-beta.6 → 3.0.1-beta.61

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 (72) hide show
  1. package/README.md +368 -65
  2. package/dist/api/arkynLogRequest.d.ts +1 -1
  3. package/dist/api/arkynLogRequest.d.ts.map +1 -1
  4. package/dist/api/arkynLogRequest.js +6 -8
  5. package/dist/api/makeRequest.d.ts +1 -1
  6. package/dist/api/makeRequest.d.ts.map +1 -1
  7. package/dist/api/makeRequest.js +3 -6
  8. package/dist/bundle.js +1098 -0
  9. package/dist/bundle.umd.cjs +8 -0
  10. package/dist/index.d.ts +3 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3 -4
  13. package/dist/mapper/arkynLogRequestMapper.js +2 -2
  14. package/dist/{config/apiInstance.d.ts → services/apiService.d.ts} +25 -21
  15. package/dist/services/apiService.d.ts.map +1 -0
  16. package/dist/{config/apiInstance.js → services/apiService.js} +40 -18
  17. package/dist/{config/arkynLogInstance.d.ts → services/arkynLogService.d.ts} +5 -5
  18. package/dist/services/arkynLogService.d.ts.map +1 -0
  19. package/dist/{config/arkynLogInstance.js → services/arkynLogService.js} +4 -5
  20. package/dist/services/formParse.d.ts +3 -3
  21. package/dist/services/formParse.d.ts.map +1 -1
  22. package/dist/services/formParse.js +8 -5
  23. package/dist/services/getCaller.d.ts.map +1 -1
  24. package/dist/services/getCaller.js +9 -14
  25. package/dist/services/httpDebug.d.ts +40 -1
  26. package/dist/services/httpDebug.d.ts.map +1 -1
  27. package/dist/services/httpDebug.js +42 -1
  28. package/dist/services/measureRouteExecution.d.ts +3 -0
  29. package/dist/services/measureRouteExecution.d.ts.map +1 -0
  30. package/dist/services/measureRouteExecution.js +24 -0
  31. package/dist/services/schemaValidator.d.ts +3 -3
  32. package/dist/services/schemaValidator.d.ts.map +1 -1
  33. package/dist/services/schemaValidator.js +1 -1
  34. package/package.json +33 -18
  35. package/dist/config/apiInstance.d.ts.map +0 -1
  36. package/dist/config/arkynLogInstance.d.ts.map +0 -1
  37. package/src/api/arkynLogRequest.ts +0 -116
  38. package/src/api/deleteRequest.ts +0 -22
  39. package/src/api/getRequest.ts +0 -20
  40. package/src/api/makeRequest.ts +0 -122
  41. package/src/api/patchRequest.ts +0 -22
  42. package/src/api/postRequest.ts +0 -22
  43. package/src/api/putRequest.ts +0 -22
  44. package/src/config/apiInstance.ts +0 -148
  45. package/src/config/arkynLogInstance.ts +0 -75
  46. package/src/http/badResponses/badGateway.ts +0 -63
  47. package/src/http/badResponses/badRequest.ts +0 -63
  48. package/src/http/badResponses/conflict.ts +0 -63
  49. package/src/http/badResponses/forbidden.ts +0 -63
  50. package/src/http/badResponses/notFound.ts +0 -63
  51. package/src/http/badResponses/notImplemented.ts +0 -63
  52. package/src/http/badResponses/serverError.ts +0 -63
  53. package/src/http/badResponses/unauthorized.ts +0 -63
  54. package/src/http/badResponses/unprocessableEntity.ts +0 -79
  55. package/src/http/successResponses/created.ts +0 -64
  56. package/src/http/successResponses/found.ts +0 -67
  57. package/src/http/successResponses/noContent.ts +0 -42
  58. package/src/http/successResponses/success.ts +0 -64
  59. package/src/http/successResponses/updated.ts +0 -64
  60. package/src/index.ts +0 -31
  61. package/src/mapper/arkynLogRequestMapper.ts +0 -73
  62. package/src/services/decodeErrorMessageFromRequest.ts +0 -36
  63. package/src/services/decodeRequestBody.ts +0 -43
  64. package/src/services/errorHandler.ts +0 -99
  65. package/src/services/formParse.ts +0 -83
  66. package/src/services/getCaller.ts +0 -82
  67. package/src/services/getScopedParams.ts +0 -43
  68. package/src/services/httpDebug.ts +0 -61
  69. package/src/services/schemaValidator.ts +0 -66
  70. package/src/types/ApiResponseDTO.ts +0 -19
  71. package/tsconfig.json +0 -21
  72. package/vitest.config.ts +0 -5
@@ -1,4 +1,45 @@
1
1
  import { getCaller } from "../services/getCaller";
2
+ /**
3
+ * Service for managing HTTP debug configuration and behavior.
4
+ *
5
+ * This service provides functionality to configure how the `getCaller` function
6
+ * identifies the actual caller in the stack trace by allowing specific files
7
+ * to be ignored during stack trace analysis.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * // Configure to ignore httpAdapter.ts in stack traces
12
+ * HttpDebugService.setIgnoreFile("httpAdapter.ts");
13
+ *
14
+ * // Now when httpDebug is called from within httpAdapter.ts,
15
+ * // it will show the actual caller (e.g., cart.ts) instead
16
+ * ```
17
+ */
18
+ class HttpDebugService {
19
+ /**
20
+ * The name of the file to ignore when analyzing the stack trace.
21
+ * When set, the `getCaller` function will skip stack frames containing this file name.
22
+ */
23
+ static ignoreFile;
24
+ /**
25
+ * Sets the file name to be ignored during stack trace analysis.
26
+ *
27
+ * This method configures the debug service to skip specific files when
28
+ * determining the actual caller of a function. This is useful when you have
29
+ * adapter or wrapper functions that you want to be transparent in the debug output.
30
+ *
31
+ * @param file - The name of the file to ignore in stack traces (e.g., "httpAdapter.ts")
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * // Ignore the HTTP adapter file so debug shows the actual business logic caller
36
+ * HttpDebugService.setIgnoreFile("httpAdapter.ts");
37
+ * ```
38
+ */
39
+ static setIgnoreFile(file) {
40
+ this.ignoreFile = file;
41
+ }
42
+ }
2
43
  /**
3
44
  * Logs debug information to the console when in development mode or when the
4
45
  * `SHOW_ERRORS_IN_CONSOLE` environment variable is set to "true".
@@ -49,4 +90,4 @@ function httpDebug(name, body, cause) {
49
90
  console.log(consoleData);
50
91
  }
51
92
  }
52
- export { httpDebug };
93
+ export { httpDebug, HttpDebugService };
@@ -0,0 +1,3 @@
1
+ declare function measureRouteExecution<T = unknown>(handler: (props: any) => Promise<T>): (props: any) => Promise<T>;
2
+ export { measureRouteExecution };
3
+ //# sourceMappingURL=measureRouteExecution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"measureRouteExecution.d.ts","sourceRoot":"","sources":["../../src/services/measureRouteExecution.ts"],"names":[],"mappings":"AAAA,iBAAS,qBAAqB,CAAC,CAAC,GAAG,OAAO,EACxC,OAAO,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,CAAC,IAEG,OAAO,GAAG,KAAG,OAAO,CAAC,CAAC,CAAC,CAyB9D;AAED,OAAO,EAAE,qBAAqB,EAAE,CAAC"}
@@ -0,0 +1,24 @@
1
+ function measureRouteExecution(handler) {
2
+ return async function measuredHandler(props) {
3
+ const startTime = performance.now();
4
+ try {
5
+ const result = await handler(props);
6
+ const url = new URL(props.request.url);
7
+ const endTime = performance.now();
8
+ const duration = (endTime - startTime).toFixed(2);
9
+ console.log({
10
+ domain: url.hostname,
11
+ pathname: url.pathname,
12
+ method: props.request.method,
13
+ duration,
14
+ });
15
+ return result;
16
+ }
17
+ catch (error) {
18
+ const endTime = performance.now();
19
+ console.error("");
20
+ throw error;
21
+ }
22
+ };
23
+ }
24
+ export { measureRouteExecution };
@@ -1,11 +1,11 @@
1
- import { Schema, z } from "zod";
2
- declare class SchemaValidator<T extends Schema> {
1
+ import { ZodType, z } from "zod";
2
+ declare class SchemaValidator<T extends ZodType> {
3
3
  readonly schema: T;
4
4
  functionName: string;
5
5
  callerInfo: string;
6
6
  constructor(schema: T);
7
7
  isValid(data: any): boolean;
8
- safeValidate(data: any): z.SafeParseReturnType<z.infer<T>, z.infer<T>>;
8
+ safeValidate(data: any): z.ZodSafeParseResult<z.infer<T>>;
9
9
  validate(data: any): z.infer<T>;
10
10
  formValidate(data: any, message?: string): z.infer<T>;
11
11
  }
@@ -1 +1 @@
1
- {"version":3,"file":"schemaValidator.d.ts","sourceRoot":"","sources":["../../src/services/schemaValidator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAiBhC,cAAM,eAAe,CAAC,CAAC,SAAS,MAAM;IAIxB,QAAQ,CAAC,MAAM,EAAE,CAAC;IAH9B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;gBAEE,MAAM,EAAE,CAAC;IAM9B,OAAO,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO;IAI3B,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAItE,QAAQ,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAQ/B,YAAY,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;CAoBtD;AAED,OAAO,EAAE,eAAe,EAAE,CAAC"}
1
+ {"version":3,"file":"schemaValidator.d.ts","sourceRoot":"","sources":["../../src/services/schemaValidator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAiBjC,cAAM,eAAe,CAAC,CAAC,SAAS,OAAO;IAIzB,QAAQ,CAAC,MAAM,EAAE,CAAC;IAH9B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;gBAEE,MAAM,EAAE,CAAC;IAM9B,OAAO,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO;IAI3B,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAIzD,QAAQ,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAQ/B,YAAY,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;CAoBtD;AAED,OAAO,EAAE,eAAe,EAAE,CAAC"}
@@ -1,4 +1,4 @@
1
- import { Schema, z } from "zod";
1
+ import { ZodType, z } from "zod";
2
2
  import { ServerError } from "../http/badResponses/serverError";
3
3
  import { UnprocessableEntity } from "../http/badResponses/unprocessableEntity";
4
4
  import { formParse } from "./formParse";
package/package.json CHANGED
@@ -1,29 +1,44 @@
1
1
  {
2
2
  "name": "@arkyn/server",
3
- "version": "3.0.1-beta.6",
3
+ "version": "3.0.1-beta.61",
4
4
  "author": "Arkyn | Lucas Gonçalves",
5
5
  "main": "./dist/bundle.js",
6
- "module": "./src/index.ts",
7
- "dependencies": {
8
- "@arkyn/shared": "*",
9
- "zod": ">=3.24.2"
10
- },
11
- "devDependencies": {
12
- "bun-types": "latest",
13
- "vitest": "^3.1.1",
14
- "typescript": "^5.8.3"
15
- },
16
- "peerDependencies": {
17
- "@react-router/node": ">=7.6.0"
18
- },
19
- "description": "Server-side utilities for projects.",
6
+ "module": "./dist/bundle.js",
7
+ "type": "module",
8
+ "types": "./dist/index.d.ts",
20
9
  "license": "Apache-2.0",
10
+ "description": "Comprehensive server-side utilities for building robust backend applications, featuring HTTP response helpers, error handlers, request utilities, and API configurations.",
11
+ "keywords": [
12
+ "server",
13
+ "http",
14
+ "api",
15
+ "utilities",
16
+ "error-handling",
17
+ "validation",
18
+ "remix",
19
+ "typescript",
20
+ "zod"
21
+ ],
22
+ "homepage": "https://docs.arkyn.dev/en/server/introduction",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/Lucas-Eduardo-Goncalves/arkyn.git",
26
+ "directory": "packages/server"
27
+ },
21
28
  "scripts": {
22
29
  "clean": "rm -rf dist",
23
- "build": "bun run clean && bunx tsc --project tsconfig.json",
30
+ "build": "bunx vite build && tsc",
24
31
  "test": "vitest --config vitest.config.ts",
25
32
  "typecheck": "bunx tsc --project tsconfig.json --noEmit"
26
33
  },
27
- "type": "module",
28
- "types": "./dist/index.d.ts"
34
+ "dependencies": {
35
+ "@arkyn/shared": "*",
36
+ "zod": "^4.0.17"
37
+ },
38
+ "devDependencies": {
39
+ "bun-types": "latest",
40
+ "vitest": "^3.2.4",
41
+ "typescript": "^5.9.2",
42
+ "vite": "^5.4.19"
43
+ }
29
44
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"apiInstance.d.ts","sourceRoot":"","sources":["../../src/config/apiInstance.ts"],"names":[],"mappings":"AAMA,KAAK,0BAA0B,GAAG;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,CAAC;AAEF,KAAK,8BAA8B,GAAG;IACpC,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,KAAK,2BAA2B,GAAG;IACjC,IAAI,CAAC,EAAE,GAAG,CAAC;IACX,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AAEH,cAAM,WAAW;IACf,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,WAAW,CAAC,CAAc;IAClC,OAAO,CAAC,SAAS,CAAC,CAAS;IAE3B;;;;;;OAMG;gBAES,KAAK,EAAE,0BAA0B;IAM7C;;;;OAIG;IAEH,OAAO,CAAC,WAAW;IAInB;;;;;OAKG;IAEH,OAAO,CAAC,eAAe;IAcvB;;;;;OAKG;IAEG,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,8BAA8B;IAM9D;;;;;OAKG;IAEG,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,2BAA2B;IAO5D;;;;;OAKG;IAEG,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,2BAA2B;IAO3D;;;;;OAKG;IAEG,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,2BAA2B;IAO7D;;;;;OAKG;IAEG,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,2BAA2B;CAM/D;AAED,OAAO,EAAE,WAAW,EAAE,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"arkynLogInstance.d.ts","sourceRoot":"","sources":["../../src/config/arkynLogInstance.ts"],"names":[],"mappings":"AAAA,KAAK,gBAAgB,GAAG;IACtB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,cAAc,EAAE,MAAM,CAAC;IACvB,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B,CAAC;AAEF;;;;GAIG;AAEH,cAAM,gBAAgB;IACpB,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAmB;IAE9C;;;;;;;;;;OAUG;IAEH,MAAM,CAAC,cAAc,CAAC,WAAW,EAAE,mBAAmB;IAqBtD;;;;;OAKG;IACH,MAAM,CAAC,cAAc,IAAI,gBAAgB,GAAG,SAAS;IAIrD;;;OAGG;IAEH,MAAM,CAAC,gBAAgB;CAGxB;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
@@ -1,116 +0,0 @@
1
- import { ArkynLogInstance } from "../config/arkynLogInstance";
2
- import { httpDebug } from "../services/httpDebug";
3
-
4
- type ConfigProps = {
5
- rawUrl: string;
6
- status: number;
7
- method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
8
- token: string | null;
9
- elapsedTime: number;
10
- requestHeaders: Record<string, string>;
11
- requestBody: Record<string, string>;
12
- queryParams: Record<string, string>;
13
- responseHeaders: Record<string, string>;
14
- responseBody: Record<string, string>;
15
- };
16
-
17
- /**
18
- * Sends a request to the inbox flow API with the provided configuration.
19
- *
20
- * @param config - The configuration object for the request.
21
- * @param config.rawUrl - The raw URL of the request.
22
- * @param config.status - The HTTP status code associated with the request.
23
- * @param config.method - The HTTP method used for the request. Can be "POST", "GET", "PUT", "DELETE", or "PATCH".
24
- * @param config.token - The authentication token for the request.
25
- * @param config.elapsedTime - The elapsed time for the request in milliseconds.
26
- * @param config.requestHeaders - The headers sent with the request.
27
- * @param config.requestBody - The body of the request, if applicable.
28
- * @param config.queryParams - The query parameters for the request.
29
- * @param config.responseHeaders - The headers received in the response.
30
- * @param config.responseBody - The body of the response received.
31
- *
32
- * @remarks
33
- * - This function retrieves the inbox flow configuration using `InboxFlowInstance.getInboxConfig()`.
34
- * - If the configuration is not available, the function will return early without performing any action.
35
- * - In a development environment (`NODE_ENV === "development"`), the function will also return early.
36
- * - The request is sent as a POST request to the inbox API URL with the provided configuration details.
37
- * - If an error occurs during the request, it will be logged using the `httpDebug` service.
38
- *
39
- * @example
40
- * ```typescript
41
- * const config = {
42
- * rawUrl: "https://example.com/api/data",
43
- * status: 200,
44
- * method: "GET",
45
- * token: "auth-token-123",
46
- * elapsedTime: "150ms",
47
- * requestHeaders: { "Accept": "application/json", "Authorization": "Bearer token123" },
48
- * requestBody: {},
49
- * queryParams: { "page": "1", "limit": "10" },
50
- * responseHeaders: { "Content-Type": "application/json" },
51
- * responseBody: { "data": "example response" }
52
- * };
53
- *
54
- * await arkynLogRequest(config);
55
- * ```
56
- */
57
-
58
- async function arkynLogRequest(config: ConfigProps) {
59
- const arkynInstance = ArkynLogInstance.getArkynConfig();
60
- console.log("arkynInstance", arkynInstance);
61
-
62
- if (!arkynInstance) return;
63
-
64
- console.log("dasd", arkynInstance);
65
-
66
- const { arkynApiUrl, arkynUserToken } = arkynInstance;
67
-
68
- const {
69
- elapsedTime,
70
- method,
71
- queryParams,
72
- requestBody,
73
- requestHeaders,
74
- responseBody,
75
- responseHeaders,
76
- status,
77
- token,
78
- rawUrl,
79
- } = config;
80
-
81
- // if (process.env.NODE_ENV === "development") return;
82
-
83
- try {
84
- const url = new URL(rawUrl);
85
- let protocol: "HTTPS" | "HTTP" = "HTTPS";
86
- if (url.protocol === "http:") protocol = "HTTP";
87
-
88
- const body = JSON.stringify({
89
- domainUrl: url.protocol + "//" + url.host,
90
- pathnameUrl: url.pathname,
91
- status,
92
- protocol,
93
- method,
94
- trafficUserId: null,
95
- elapsedTime,
96
- requestHeaders,
97
- requestBody,
98
- queryParams,
99
- responseHeaders,
100
- responseBody,
101
- });
102
-
103
- await fetch(arkynApiUrl, {
104
- method: "POST",
105
- body,
106
- headers: {
107
- "Content-Type": "application/json",
108
- Authorization: `Bearer ${arkynUserToken}`,
109
- },
110
- });
111
- } catch (err) {
112
- httpDebug("arkyn log error", "Error sending request", err);
113
- }
114
- }
115
-
116
- export { arkynLogRequest };
@@ -1,22 +0,0 @@
1
- import type { ApiResponseDTO } from "../types/ApiResponseDTO";
2
- import { makeRequest } from "./makeRequest";
3
-
4
- /**
5
- * Sends a DELETE request to the specified URL with optional headers and body.
6
- *
7
- * @template T - The expected type of the response data.
8
- * @param {string} url - The URL to send the DELETE request to.
9
- * @param {HeadersInit} [headers={}] - Optional headers to include in the request.
10
- * @param {any} [body] - Optional body to include in the request.
11
- * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
12
- */
13
-
14
- async function deleteRequest<T = any>(
15
- url: string,
16
- headers: HeadersInit = {},
17
- body?: any
18
- ): Promise<ApiResponseDTO<T>> {
19
- return makeRequest("DELETE", url, headers, body);
20
- }
21
-
22
- export { deleteRequest };
@@ -1,20 +0,0 @@
1
- import type { ApiResponseDTO } from "../types/ApiResponseDTO";
2
- import { makeRequest } from "./makeRequest";
3
-
4
- /**
5
- * Sends a GET request to the specified URL with optional headers.
6
- *
7
- * @template T - The expected type of the response data.
8
- * @param {string} url - The URL to send the GET request to.
9
- * @param {HeadersInit} [headers={}] - Optional headers to include in the request.
10
- * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
11
- */
12
-
13
- async function getRequest<T = any>(
14
- url: string,
15
- headers: HeadersInit = {}
16
- ): Promise<ApiResponseDTO<T>> {
17
- return makeRequest("GET", url, headers);
18
- }
19
-
20
- export { getRequest };
@@ -1,122 +0,0 @@
1
- import { ArkynLogRequestMapper } from "../mapper/arkynLogRequestMapper";
2
- import { httpDebug } from "../services/httpDebug";
3
- import type { ApiResponseDTO } from "../types/ApiResponseDTO";
4
- import { arkynLogRequest } from "./arkynLogRequest";
5
-
6
- /**
7
- * Makes an HTTP request using the Fetch API and returns a standardized response.
8
- *
9
- * @template T - The expected type of the response data.
10
- * @param method - The HTTP method to use for the request. Supported methods are:
11
- * - "POST": Create a new resource.
12
- * - "PUT": Update an existing resource.
13
- * - "DELETE": Remove a resource.
14
- * - "PATCH": Partially update a resource.
15
- * - "GET": Retrieve a resource.
16
- * @param url - The URL to which the request is sent.
17
- * @param headers - Optional headers to include in the request. Defaults to an empty object.
18
- * @param body - Optional body to include in the request. Should be serializable to JSON.
19
- * @returns A promise that resolves to an `ApiResponseDTO<T>` object containing:
20
- * - `success`: A boolean indicating whether the request was successful.
21
- * - `status`: The HTTP status code of the response.
22
- * - `message`: A message describing the result of the request.
23
- * - `response`: The parsed JSON response data, or `null` if parsing fails.
24
- * - `cause`: Additional error information, if applicable.
25
- *
26
- * @example
27
- * ```typescript
28
- * import { makeRequest } from "./makeRequest";
29
- *
30
- * async function fetchData() {
31
- * const response = await makeRequest("GET", "https://api.example.com/data");
32
- * if (response.success) {
33
- * console.log("Data:", response.response);
34
- * } else {
35
- * console.error("Error:", response.message);
36
- * }
37
- * }
38
- * ```
39
- */
40
-
41
- async function makeRequest<T = any>(
42
- method: "POST" | "PUT" | "DELETE" | "PATCH" | "GET",
43
- url: string,
44
- headers: HeadersInit = {},
45
- body?: any
46
- ): Promise<ApiResponseDTO<T>> {
47
- const successMessage = {
48
- POST: "Resource created successfully",
49
- PUT: "Resource updated successfully",
50
- DELETE: "Resource deleted successfully",
51
- PATCH: "Resource patched successfully",
52
- GET: "Request successful",
53
- };
54
-
55
- try {
56
- const startTime = performance.now();
57
-
58
- const response = await fetch(url, {
59
- method,
60
- headers: {
61
- ...headers,
62
- "Content-Type": "application/json",
63
- },
64
- body: body ? JSON.stringify(body) : undefined,
65
- });
66
-
67
- const elapsedTime = performance.now() - startTime;
68
- const status = response.status;
69
-
70
- let data: any = null;
71
- try {
72
- data = await response.json();
73
- } catch {
74
- data = null;
75
- }
76
-
77
- const logData = ArkynLogRequestMapper.handle({
78
- elapsedTime,
79
- method,
80
- queryParams: new URL(url).searchParams,
81
- requestHeaders: headers,
82
- requestBody: body,
83
- responseBody: data,
84
- responseHeaders: response.headers,
85
- status,
86
- url,
87
- });
88
-
89
- console.log("Request Log Data:", logData);
90
-
91
- arkynLogRequest(logData);
92
-
93
- if (!response.ok) {
94
- return {
95
- success: false,
96
- status,
97
- message: data?.message || response.statusText || "Request failed",
98
- response: data,
99
- cause: null,
100
- };
101
- }
102
-
103
- return {
104
- success: true,
105
- status,
106
- message: data?.message || successMessage[method],
107
- response: data,
108
- cause: null,
109
- };
110
- } catch (err) {
111
- httpDebug("Network error or request failed", null, err);
112
- return {
113
- success: false,
114
- status: 0,
115
- message: "Network error or request failed",
116
- response: null,
117
- cause: err instanceof Error ? err.message : String(err),
118
- };
119
- }
120
- }
121
-
122
- export { makeRequest };
@@ -1,22 +0,0 @@
1
- import type { ApiResponseDTO } from "../types/ApiResponseDTO";
2
- import { makeRequest } from "./makeRequest";
3
-
4
- /**
5
- * Sends a PATCH request to the specified URL with optional headers and body.
6
- *
7
- * @template T - The expected type of the response data.
8
- * @param {string} url - The URL to send the PATCH request to.
9
- * @param {HeadersInit} [headers={}] - Optional headers to include in the request.
10
- * @param {any} body - The body to include in the request.
11
- * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
12
- */
13
-
14
- async function patchRequest<T = any>(
15
- url: string,
16
- headers: HeadersInit = {},
17
- body: any
18
- ): Promise<ApiResponseDTO<T>> {
19
- return makeRequest("PATCH", url, headers, body);
20
- }
21
-
22
- export { patchRequest };
@@ -1,22 +0,0 @@
1
- import type { ApiResponseDTO } from "../types/ApiResponseDTO";
2
- import { makeRequest } from "./makeRequest";
3
-
4
- /**
5
- * Sends a PATCH request to the specified URL with optional headers and body.
6
- *
7
- * @template T - The expected type of the response data.
8
- * @param {string} url - The URL to send the PATCH request to.
9
- * @param {HeadersInit} [headers={}] - Optional headers to include in the request.
10
- * @param {any} body - The body to include in the request.
11
- * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
12
- */
13
-
14
- async function postRequest<T = any>(
15
- url: string,
16
- headers: HeadersInit = {},
17
- body: any
18
- ): Promise<ApiResponseDTO<T>> {
19
- return makeRequest("POST", url, headers, body);
20
- }
21
-
22
- export { postRequest };
@@ -1,22 +0,0 @@
1
- import type { ApiResponseDTO } from "../types/ApiResponseDTO";
2
- import { makeRequest } from "./makeRequest";
3
-
4
- /**
5
- * Sends a PATCH request to the specified URL with optional headers and body.
6
- *
7
- * @template T - The expected type of the response data.
8
- * @param {string} url - The URL to send the PATCH request to.
9
- * @param {HeadersInit} [headers={}] - Optional headers to include in the request.
10
- * @param {any} body - The body to include in the request.
11
- * @returns {Promise<ApiResponseDTO<T>>} A promise that resolves to the API response.
12
- */
13
-
14
- async function putRequest<T = any>(
15
- url: string,
16
- headers: HeadersInit = {},
17
- body: any
18
- ): Promise<ApiResponseDTO<T>> {
19
- return makeRequest("PUT", url, headers, body);
20
- }
21
-
22
- export { putRequest };