@arkyn/server 3.0.1-beta.31 → 3.0.1-beta.33

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 (36) hide show
  1. package/package.json +3 -3
  2. package/src/api/arkynLogRequest.ts +118 -0
  3. package/src/api/deleteRequest.ts +22 -0
  4. package/src/api/getRequest.ts +20 -0
  5. package/src/api/makeRequest.ts +118 -0
  6. package/src/api/patchRequest.ts +22 -0
  7. package/src/api/postRequest.ts +22 -0
  8. package/src/api/putRequest.ts +22 -0
  9. package/src/config/apiInstance.ts +148 -0
  10. package/src/config/arkynLogInstance.ts +70 -0
  11. package/src/http/badResponses/badGateway.ts +63 -0
  12. package/src/http/badResponses/badRequest.ts +63 -0
  13. package/src/http/badResponses/conflict.ts +63 -0
  14. package/src/http/badResponses/forbidden.ts +63 -0
  15. package/src/http/badResponses/notFound.ts +63 -0
  16. package/src/http/badResponses/notImplemented.ts +63 -0
  17. package/src/http/badResponses/serverError.ts +63 -0
  18. package/src/http/badResponses/unauthorized.ts +63 -0
  19. package/src/http/badResponses/unprocessableEntity.ts +79 -0
  20. package/src/http/successResponses/created.ts +64 -0
  21. package/src/http/successResponses/found.ts +67 -0
  22. package/src/http/successResponses/noContent.ts +42 -0
  23. package/src/http/successResponses/success.ts +64 -0
  24. package/src/http/successResponses/updated.ts +64 -0
  25. package/src/index.ts +31 -0
  26. package/src/mapper/arkynLogRequestMapper.ts +73 -0
  27. package/src/services/decodeErrorMessageFromRequest.ts +36 -0
  28. package/src/services/decodeRequestBody.ts +43 -0
  29. package/src/services/errorHandler.ts +99 -0
  30. package/src/services/formParse.ts +86 -0
  31. package/src/services/getCaller.ts +82 -0
  32. package/src/services/getScopedParams.ts +43 -0
  33. package/src/services/httpDebug.ts +61 -0
  34. package/src/services/measureRouteExecution.ts +31 -0
  35. package/src/services/schemaValidator.ts +66 -0
  36. package/src/types/ApiResponseDTO.ts +19 -0
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@arkyn/server",
3
- "version": "3.0.1-beta.31",
3
+ "version": "3.0.1-beta.33",
4
4
  "author": "Arkyn | Lucas Gonçalves",
5
5
  "main": "./dist/index.js",
6
- "module": "./dist/index.js",
6
+ "module": "./src/index.ts",
7
7
  "type": "module",
8
- "types": "./dist/index.d.ts",
8
+ "types": "./src/index.ts",
9
9
  "license": "Apache-2.0",
10
10
  "description": "Comprehensive server-side utilities for building robust backend applications, featuring HTTP response helpers, error handlers, request utilities, and API configurations.",
11
11
  "keywords": [
@@ -0,0 +1,118 @@
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
+ if (!arkynInstance) return;
61
+
62
+ const { arkynUserToken, arkynApiUrl } = arkynInstance;
63
+
64
+ const {
65
+ elapsedTime,
66
+ method,
67
+ queryParams,
68
+ requestBody,
69
+ requestHeaders,
70
+ responseBody,
71
+ responseHeaders,
72
+ status,
73
+ token,
74
+ rawUrl,
75
+ } = config;
76
+
77
+ // if (process.env.NODE_ENV === "development") return;
78
+
79
+ try {
80
+ const url = new URL(rawUrl);
81
+ let protocol: "HTTPS" | "HTTP" = "HTTPS";
82
+ if (url.protocol === "http:") protocol = "HTTP";
83
+
84
+ const body = JSON.stringify({
85
+ domainUrl: url.protocol + "//" + url.host,
86
+ pathnameUrl: url.pathname,
87
+ status,
88
+ protocol,
89
+ method,
90
+ trafficUserId: null,
91
+ elapsedTime,
92
+ requestHeaders,
93
+ requestBody,
94
+ queryParams,
95
+ responseHeaders,
96
+ responseBody,
97
+ });
98
+
99
+ await fetch(
100
+ arkynApiUrl.replace(
101
+ ":trafficSourceId",
102
+ arkynInstance.arkynTrafficSourceId
103
+ ),
104
+ {
105
+ method: "POST",
106
+ body,
107
+ headers: {
108
+ "Content-Type": "application/json",
109
+ Authorization: `Bearer ${arkynUserToken}`,
110
+ },
111
+ }
112
+ );
113
+ } catch (err) {
114
+ httpDebug("arkyn log error", "Error sending request", err);
115
+ }
116
+ }
117
+
118
+ export { arkynLogRequest };
@@ -0,0 +1,22 @@
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 };
@@ -0,0 +1,20 @@
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 };
@@ -0,0 +1,118 @@
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
+ rawHeaders: 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 headers = { ...rawHeaders, "Content-Type": "application/json" };
59
+ const response = await fetch(url, {
60
+ method,
61
+ headers,
62
+ body: body ? JSON.stringify(body) : undefined,
63
+ });
64
+
65
+ const elapsedTime = performance.now() - startTime;
66
+ const status = response.status;
67
+
68
+ let data: any = null;
69
+ try {
70
+ data = await response.json();
71
+ } catch {
72
+ data = null;
73
+ }
74
+
75
+ const logData = ArkynLogRequestMapper.handle({
76
+ elapsedTime,
77
+ method,
78
+ queryParams: new URL(url).searchParams,
79
+ requestHeaders: headers,
80
+ requestBody: body,
81
+ responseBody: data,
82
+ responseHeaders: response.headers,
83
+ status,
84
+ url,
85
+ });
86
+
87
+ arkynLogRequest(logData);
88
+
89
+ if (!response.ok) {
90
+ return {
91
+ success: false,
92
+ status,
93
+ message: data?.message || response.statusText || "Request failed",
94
+ response: data,
95
+ cause: null,
96
+ };
97
+ }
98
+
99
+ return {
100
+ success: true,
101
+ status,
102
+ message: data?.message || successMessage[method],
103
+ response: data,
104
+ cause: null,
105
+ };
106
+ } catch (err) {
107
+ httpDebug("Network error or request failed", null, err);
108
+ return {
109
+ success: false,
110
+ status: 0,
111
+ message: "Network error or request failed",
112
+ response: null,
113
+ cause: err instanceof Error ? err.message : String(err),
114
+ };
115
+ }
116
+ }
117
+
118
+ export { makeRequest };
@@ -0,0 +1,22 @@
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 };
@@ -0,0 +1,22 @@
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 };
@@ -0,0 +1,22 @@
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 };
@@ -0,0 +1,148 @@
1
+ import { deleteRequest } from "../api/deleteRequest";
2
+ import { getRequest } from "../api/getRequest";
3
+ import { patchRequest } from "../api/patchRequest";
4
+ import { postRequest } from "../api/postRequest";
5
+ import { putRequest } from "../api/putRequest";
6
+
7
+ type ApiInstanceConstructorProps = {
8
+ baseUrl: string;
9
+ baseHeaders?: HeadersInit;
10
+ baseToken?: string | null;
11
+ };
12
+
13
+ type ApiRequestDataWithoutBodyProps = {
14
+ headers?: HeadersInit;
15
+ token?: string;
16
+ };
17
+
18
+ type ApiRequestDataWithBodyProps = {
19
+ body?: any;
20
+ headers?: HeadersInit;
21
+ token?: string;
22
+ };
23
+
24
+ /**
25
+ * Class representing an API instance to handle HTTP requests with base configurations.
26
+ */
27
+
28
+ class ApiInstance {
29
+ private baseUrl: string;
30
+ private baseHeaders?: HeadersInit;
31
+ private baseToken?: string;
32
+
33
+ /**
34
+ * Creates an instance of ApiInstance.
35
+ * @param props - The configuration properties for the API instance.
36
+ * @param props.baseUrl - The base URL for the API.
37
+ * @param props.baseHeaders - Optional base headers to include in all requests.
38
+ * @param props.baseToken - Optional base token for authorization.
39
+ */
40
+
41
+ constructor(props: ApiInstanceConstructorProps) {
42
+ this.baseUrl = props.baseUrl;
43
+ this.baseHeaders = props.baseHeaders || undefined;
44
+ this.baseToken = props.baseToken || undefined;
45
+ }
46
+
47
+ /**
48
+ * Generates the full URL by appending the route to the base URL.
49
+ * @param route - The route to append to the base URL.
50
+ * @returns The full URL as a string.
51
+ */
52
+
53
+ private generateURL(route: string) {
54
+ return this.baseUrl + route;
55
+ }
56
+
57
+ /**
58
+ * Generates the headers for a request by merging base headers, provided headers, and tokens.
59
+ * @param initHeaders - Initial headers to include in the request.
60
+ * @param token - Optional token to override the base token.
61
+ * @returns The merged headers as a HeadersInit object.
62
+ */
63
+
64
+ private generateHeaders(
65
+ initHeaders: HeadersInit,
66
+ token?: string
67
+ ): HeadersInit {
68
+ let headers: HeadersInit = {};
69
+ if (this.baseToken) headers = { Authorization: `Bearer ${this.baseToken}` };
70
+ if (this.baseHeaders) headers = { ...headers, ...this.baseHeaders };
71
+
72
+ if (initHeaders) headers = { ...headers, ...initHeaders };
73
+ if (token) headers = { ...headers, Authorization: `Bearer ${token}` };
74
+
75
+ return headers;
76
+ }
77
+
78
+ /**
79
+ * Sends a get request to the specified route.
80
+ * @param route - The API route to send the get request to.
81
+ * @param data - The request data, including optional headers and token.
82
+ * @returns The API response data.
83
+ */
84
+
85
+ async get(route: string, data?: ApiRequestDataWithoutBodyProps) {
86
+ const url = this.generateURL(route);
87
+ const headers = this.generateHeaders(data?.headers || {}, data?.token);
88
+ return await getRequest(url, headers);
89
+ }
90
+
91
+ /**
92
+ * Sends a post request to the specified route.
93
+ * @param route - The API route to send the post request to.
94
+ * @param data - The request data, including body, optional headers, and token.
95
+ * @returns The API response data.
96
+ */
97
+
98
+ async post(route: string, data?: ApiRequestDataWithBodyProps) {
99
+ const url = this.generateURL(route);
100
+ const headers = this.generateHeaders(data?.headers || {}, data?.token);
101
+ const body = data?.body;
102
+ return await postRequest(url, headers, body);
103
+ }
104
+
105
+ /**
106
+ * Sends a put request to the specified route.
107
+ * @param route - The API route to send the put request to.
108
+ * @param data - The request data, including body, optional headers, and token.
109
+ * @returns The API response data.
110
+ */
111
+
112
+ async put(route: string, data?: ApiRequestDataWithBodyProps) {
113
+ const url = this.generateURL(route);
114
+ const headers = this.generateHeaders(data?.headers || {}, data?.token);
115
+ const body = data?.body;
116
+ return await putRequest(url, headers, body);
117
+ }
118
+
119
+ /**
120
+ * Sends a patch request to the specified route.
121
+ * @param route - The API route to send the patch request to.
122
+ * @param data - The request data, including body, optional headers, and token.
123
+ * @returns The API response data.
124
+ */
125
+
126
+ async patch(route: string, data?: ApiRequestDataWithBodyProps) {
127
+ const url = this.generateURL(route);
128
+ const headers = this.generateHeaders(data?.headers || {}, data?.token);
129
+ const body = data?.body;
130
+ return await patchRequest(url, headers, body);
131
+ }
132
+
133
+ /**
134
+ * Sends a delete request to the specified route.
135
+ * @param route - The API route to send the delete request to.
136
+ * @param data - The request data, including body, optional headers, and token.
137
+ * @returns The API response data.
138
+ */
139
+
140
+ async delete(route: string, data?: ApiRequestDataWithBodyProps) {
141
+ const url = this.generateURL(route);
142
+ const headers = this.generateHeaders(data?.headers || {}, data?.token);
143
+ const body = data?.body;
144
+ return await deleteRequest(url, headers, body);
145
+ }
146
+ }
147
+
148
+ export { ApiInstance };
@@ -0,0 +1,70 @@
1
+ type ArkynConfigProps = {
2
+ arkynTrafficSourceId: string;
3
+ arkynUserToken: string;
4
+ arkynApiUrl: string;
5
+ };
6
+
7
+ type SetArkynConfigProps = {
8
+ arkynTrafficSourceId: string;
9
+ arkynUserToken: string;
10
+ arkynLogBaseApiUrl?: string;
11
+ };
12
+
13
+ /**
14
+ * The `ArkynLogInstance` class manages the configuration for the arkyn flow.
15
+ * It allows you to set and retrieve the arkyn configuration, including the traffic source ID,
16
+ * user token, and API URL.
17
+ */
18
+
19
+ class ArkynLogInstance {
20
+ private static arkynConfig?: ArkynConfigProps;
21
+
22
+ /**
23
+ * Sets the configuration for the arkyn. This method initializes the arkyn configuration
24
+ * with the provided `arkynConfig` values. If the configuration has already been set,
25
+ * the method will return early without making any changes.
26
+ *
27
+ * @param arkynConfig - An object containing the arkyn configuration properties.
28
+ * @param arkynConfig.arkynTrafficSourceId - The key used to identify the arkyn.
29
+ * @param arkynConfig.arkynUserToken - The user token for authenticating with the arkyn.
30
+ * @param arkynConfig.arkynLogBaseApiUrl - (Optional) The API URL for the arkyn. If not provided,
31
+ * a default URL will be used.
32
+ */
33
+
34
+ static setArkynConfig(arkynConfig: SetArkynConfigProps) {
35
+ if (!!this.arkynConfig) return;
36
+
37
+ let defaultArkynURL = `https://logs-arkyn-flow-logs.vw6wo7.easypanel.host`;
38
+ let arkynLogBaseApiUrl = arkynConfig.arkynLogBaseApiUrl || defaultArkynURL;
39
+
40
+ arkynLogBaseApiUrl =
41
+ arkynLogBaseApiUrl + "/http-traffic-records/:trafficSourceId";
42
+
43
+ this.arkynConfig = {
44
+ arkynTrafficSourceId: arkynConfig.arkynTrafficSourceId,
45
+ arkynUserToken: arkynConfig.arkynUserToken,
46
+ arkynApiUrl: arkynLogBaseApiUrl,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Retrieves the current arkyn configuration for the ArkynLogInstance.
52
+ *
53
+ * @returns {ArkynConfigProps | undefined} The current arkyn configuration if set,
54
+ * or `undefined` if no configuration has been initialized.
55
+ */
56
+ static getArkynConfig(): ArkynConfigProps | undefined {
57
+ return this.arkynConfig;
58
+ }
59
+
60
+ /**
61
+ * Resets the arkyn configuration to `undefined`.
62
+ * This method can be used to clear the current configuration.
63
+ */
64
+
65
+ static resetArkynConfig() {
66
+ this.arkynConfig = undefined;
67
+ }
68
+ }
69
+
70
+ export { ArkynLogInstance };
@@ -0,0 +1,63 @@
1
+ import { httpDebug } from "../../services/httpDebug";
2
+
3
+ /**
4
+ * Represents an HTTP error response with a status code of 502 (Bad Gateway).
5
+ * This class is used to standardize the structure of a "Bad Gateway" error response,
6
+ * including the response body, headers, status, and status text.
7
+ */
8
+
9
+ class BadGateway {
10
+ body: any;
11
+ cause?: any;
12
+ status: number = 502;
13
+ statusText: string;
14
+
15
+ /**
16
+ * Creates an instance of the `BadGateway` class.
17
+ *
18
+ * @param message - A descriptive message explaining the cause of the error.
19
+ * @param cause - Optional additional information about the cause of the error.
20
+ */
21
+
22
+ constructor(message: string, cause?: any) {
23
+ this.body = { name: "BadGateway", message: message };
24
+ this.statusText = message;
25
+ this.cause = cause ? JSON.stringify(cause) : undefined;
26
+ httpDebug("BadGateway", this.body, this.cause);
27
+ }
28
+
29
+ /**
30
+ * Converts the `BadGateway` instance into a `Response` object with a JSON body.
31
+ * This method ensures the response has the appropriate headers, status, and status text.
32
+ *
33
+ * @returns A `Response` object with the serialized JSON body and response metadata.
34
+ */
35
+
36
+ toResponse(): Response {
37
+ const responseInit: ResponseInit = {
38
+ headers: { "Content-Type": "application/json" },
39
+ status: this.status,
40
+ statusText: this.statusText,
41
+ };
42
+
43
+ return new Response(JSON.stringify(this.body), responseInit);
44
+ }
45
+
46
+ /**
47
+ * Converts the `BadGateway` instance into a `Response` object using the `Response.json` method.
48
+ * This method is an alternative to `toResponse` for generating JSON error responses.
49
+ *
50
+ * @returns A `Response` object with the JSON body and response metadata.
51
+ */
52
+
53
+ toJson(): Response {
54
+ const responseInit: ResponseInit = {
55
+ status: this.status,
56
+ statusText: this.statusText,
57
+ };
58
+
59
+ return Response.json(this.body, responseInit);
60
+ }
61
+ }
62
+
63
+ export { BadGateway };