@arkyn/server 3.0.1-beta.2 → 3.0.1-beta.21

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 (53) hide show
  1. package/README.md +1 -1
  2. package/dist/api/arkynLogRequest.d.ts +55 -0
  3. package/dist/api/arkynLogRequest.d.ts.map +1 -0
  4. package/dist/api/arkynLogRequest.js +82 -0
  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 +18 -17
  8. package/dist/config/apiInstance.d.ts +17 -17
  9. package/dist/config/apiInstance.d.ts.map +1 -1
  10. package/dist/config/apiInstance.js +15 -15
  11. package/dist/config/arkynLogInstance.d.ts +44 -0
  12. package/dist/config/arkynLogInstance.d.ts.map +1 -0
  13. package/dist/config/arkynLogInstance.js +49 -0
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/mapper/arkynLogRequestMapper.d.ts +30 -0
  18. package/dist/mapper/arkynLogRequestMapper.d.ts.map +1 -0
  19. package/dist/mapper/arkynLogRequestMapper.js +44 -0
  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 +41 -15
  25. package/dist/services/httpDebug.d.ts.map +1 -1
  26. package/dist/services/httpDebug.js +0 -1
  27. package/dist/services/measureRouteExecution.d.ts +3 -0
  28. package/dist/services/measureRouteExecution.d.ts.map +1 -0
  29. package/dist/services/measureRouteExecution.js +24 -0
  30. package/dist/services/schemaValidator.d.ts +3 -3
  31. package/dist/services/schemaValidator.d.ts.map +1 -1
  32. package/dist/services/schemaValidator.js +1 -1
  33. package/package.json +16 -19
  34. package/src/api/arkynLogRequest.ts +118 -0
  35. package/src/api/makeRequest.ts +20 -18
  36. package/src/config/apiInstance.ts +17 -17
  37. package/src/config/arkynLogInstance.ts +70 -0
  38. package/src/index.ts +1 -1
  39. package/src/mapper/arkynLogRequestMapper.ts +73 -0
  40. package/src/services/formParse.ts +11 -8
  41. package/src/services/getCaller.ts +54 -20
  42. package/src/services/httpDebug.ts +0 -1
  43. package/src/services/measureRouteExecution.ts +31 -0
  44. package/src/services/schemaValidator.ts +4 -4
  45. package/tsconfig.json +2 -2
  46. package/dist/api/inboxFlowRequest.d.ts +0 -40
  47. package/dist/api/inboxFlowRequest.d.ts.map +0 -1
  48. package/dist/api/inboxFlowRequest.js +0 -63
  49. package/dist/config/inboxFlowInstance.d.ts +0 -44
  50. package/dist/config/inboxFlowInstance.d.ts.map +0 -1
  51. package/dist/config/inboxFlowInstance.js +0 -46
  52. package/src/api/inboxFlowRequest.ts +0 -76
  53. package/src/config/inboxFlowInstance.ts +0 -65
@@ -0,0 +1,73 @@
1
+ type InputProps = {
2
+ status: number;
3
+ url: string;
4
+ method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
5
+ requestHeaders: HeadersInit;
6
+ responseHeaders: HeadersInit;
7
+ requestBody: any;
8
+ elapsedTime: number;
9
+ responseBody: any;
10
+ queryParams: URLSearchParams;
11
+ };
12
+
13
+ type OutputProps = {
14
+ rawUrl: string;
15
+ status: number;
16
+ method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
17
+ token: string | null;
18
+ elapsedTime: number;
19
+ requestHeaders: Record<string, string>;
20
+ requestBody: Record<string, string>;
21
+ queryParams: Record<string, string>;
22
+ responseHeaders: Record<string, string>;
23
+ responseBody: any;
24
+ };
25
+
26
+ class ArkynLogRequestMapper {
27
+ private static mapHeaders(headers: HeadersInit): Record<string, string> {
28
+ if (headers instanceof Headers) {
29
+ return Object.fromEntries(headers.entries());
30
+ } else if (typeof headers === "object") {
31
+ return Object.entries(headers).reduce((acc, [key, value]) => {
32
+ if (typeof value === "string") {
33
+ acc[key] = value;
34
+ } else if (Array.isArray(value)) {
35
+ acc[key] = value.join(", ");
36
+ } else {
37
+ acc[key] = JSON.stringify(value);
38
+ }
39
+ return acc;
40
+ }, {} as Record<string, string>);
41
+ }
42
+ return {};
43
+ }
44
+
45
+ private static mapQueryParams(
46
+ queryParams: URLSearchParams
47
+ ): Record<string, string> {
48
+ const params: Record<string, string> = {};
49
+
50
+ queryParams.forEach((value, key) => {
51
+ params[key] = value;
52
+ });
53
+
54
+ return params;
55
+ }
56
+
57
+ static handle(props: InputProps): OutputProps {
58
+ return {
59
+ rawUrl: props.url,
60
+ status: props.status,
61
+ method: props.method,
62
+ token: null,
63
+ elapsedTime: props.elapsedTime,
64
+ requestHeaders: this.mapHeaders(props.requestHeaders),
65
+ requestBody: props.requestBody || null,
66
+ queryParams: this.mapQueryParams(props.queryParams),
67
+ responseHeaders: this.mapHeaders(props.responseHeaders),
68
+ responseBody: props.responseBody || null,
69
+ };
70
+ }
71
+ }
72
+
73
+ export { ArkynLogRequestMapper };
@@ -1,8 +1,8 @@
1
- import type { Schema } from "zod";
1
+ import type { ZodType } from "zod";
2
2
 
3
3
  type SuccessResponse<T extends FormParseProps> = {
4
4
  success: true;
5
- data: T[1] extends Schema<infer U> ? U : never;
5
+ data: T[1] extends ZodType<infer U> ? U : never;
6
6
  };
7
7
 
8
8
  type ErrorResponse = {
@@ -11,7 +11,7 @@ type ErrorResponse = {
11
11
  fieldErrors: { [x: string]: string };
12
12
  };
13
13
 
14
- type FormParseProps = [formData: { [k: string]: any }, schema: Schema];
14
+ type FormParseProps = [formData: { [k: string]: any }, schema: ZodType];
15
15
 
16
16
  type FormParseReturnType<T extends FormParseProps> =
17
17
  | SuccessResponse<T>
@@ -64,10 +64,10 @@ function formParse<T extends FormParseProps>([
64
64
 
65
65
  if (zodResponse.success === false) {
66
66
  const errorsObject = Object.fromEntries(
67
- zodResponse.error.errors.map((item) => [
68
- item.path.join("."),
69
- item.message,
70
- ])
67
+ zodResponse.error.issues.map((item) => {
68
+ console.log(item);
69
+ return [item.path.join("."), item.message];
70
+ })
71
71
  );
72
72
 
73
73
  return {
@@ -76,7 +76,10 @@ function formParse<T extends FormParseProps>([
76
76
  fields: formData,
77
77
  };
78
78
  } else {
79
- return { success: zodResponse.success, data: zodResponse.data };
79
+ return {
80
+ success: zodResponse.success,
81
+ data: zodResponse.data as T[1] extends ZodType<infer U> ? U : never,
82
+ };
80
83
  }
81
84
  }
82
85
 
@@ -11,36 +11,70 @@ import path from "path";
11
11
  * - `functionName`: The name of the function that called the current function, or "Unknown function" if it cannot be determined.
12
12
  * - `callerInfo`: The file path of the caller relative to the project root, or "Unknown caller" if it cannot be determined.
13
13
  */
14
-
15
14
  function getCaller() {
16
15
  const projectRoot = process.cwd();
17
16
 
18
17
  const err = new Error();
19
18
  const stack = err.stack || "";
20
-
21
19
  const stackLines = stack.split("\n").map((line) => line.trim());
22
20
 
23
- const callerLine = stackLines[4] || "";
24
-
25
- let functionName = "unknown";
26
- let callerInfo = "unknown location";
27
-
28
- const functionMatch = callerLine.match(/at\s+([^\s]+)\s+\((.*)\)/);
29
- if (functionMatch) {
30
- functionName = functionMatch[1];
31
- callerInfo = functionMatch[2];
32
- } else {
33
- const locationMatch = callerLine.match(/at\s+(.*)/);
34
- if (locationMatch) {
35
- callerInfo = locationMatch[1];
36
- const pathParts = callerInfo.split("/");
37
- const lastPart = pathParts[pathParts.length - 1] || "";
38
- const fileParts = lastPart.split(":");
39
- functionName = fileParts[0] || "unknown";
21
+ // The first line is the error message
22
+ // The second line is this function (getCaller)
23
+ // The third line should be the direct caller
24
+ // We start from 2 because indexes are zero-based
25
+ let callerIndex = 2;
26
+
27
+ // Ignore internal or infrastructure lines if necessary
28
+ while (
29
+ callerIndex < stackLines.length &&
30
+ (stackLines[callerIndex].includes("node:internal") ||
31
+ stackLines[callerIndex].includes("/node_modules/"))
32
+ ) {
33
+ callerIndex++;
34
+ }
35
+
36
+ const callerLine = stackLines[callerIndex] || "";
37
+
38
+ let functionName = "Unknown function";
39
+ let callerInfo = "Unknown caller";
40
+
41
+ // Default for named functions: "at functionName (file:line:column)"
42
+ const namedFunctionMatch = callerLine.match(/at\s+([^(\s]+)\s+\(([^)]+)\)/);
43
+ if (namedFunctionMatch) {
44
+ functionName = namedFunctionMatch[1];
45
+ callerInfo = namedFunctionMatch[2];
46
+ }
47
+ // Default for anonymous functions or methods: "at file:line:column"
48
+ else {
49
+ const anonymousFunctionMatch = callerLine.match(/at\s+(.+)/);
50
+ if (anonymousFunctionMatch) {
51
+ callerInfo = anonymousFunctionMatch[1];
52
+
53
+ // Tenta extrair nome da função de padrões como Object.method ou Class.method
54
+ const objectMethodMatch = callerInfo.match(/at\s+([^(\s]+)\s+/);
55
+ if (objectMethodMatch && objectMethodMatch[1] !== "new") {
56
+ functionName = objectMethodMatch[1];
57
+ }
40
58
  }
41
59
  }
42
60
 
43
- callerInfo = path.relative(projectRoot, callerInfo);
61
+ // Handles file paths
62
+ if (callerInfo.includes("(")) {
63
+ callerInfo = callerInfo.substring(
64
+ callerInfo.indexOf("(") + 1,
65
+ callerInfo.lastIndexOf(")")
66
+ );
67
+ }
68
+
69
+ // Remove the line:column part of the file path
70
+ callerInfo = callerInfo.split(":").slice(0, -2).join(":");
71
+
72
+ // Make the path relative to the project
73
+ try {
74
+ callerInfo = path.relative(projectRoot, callerInfo);
75
+ } catch (e) {
76
+ // If it fails to relativize, use the original path
77
+ }
44
78
 
45
79
  return { functionName, callerInfo };
46
80
  }
@@ -1,4 +1,3 @@
1
- import { InboxFlowInstance } from "../config/inboxFlowInstance";
2
1
  import { getCaller } from "../services/getCaller";
3
2
 
4
3
  /**
@@ -0,0 +1,31 @@
1
+ function measureRouteExecution<T = unknown>(
2
+ handler: (props: any) => Promise<T>
3
+ ) {
4
+ return async function measuredHandler(props: any): Promise<T> {
5
+ const startTime = performance.now();
6
+
7
+ try {
8
+ const result = await handler(props);
9
+
10
+ const url = new URL(props.request.url);
11
+ const endTime = performance.now();
12
+
13
+ const duration = (endTime - startTime).toFixed(2);
14
+
15
+ console.log({
16
+ domain: url.hostname,
17
+ pathname: url.pathname,
18
+ method: props.request.method,
19
+ duration,
20
+ });
21
+
22
+ return result as T;
23
+ } catch (error) {
24
+ const endTime = performance.now();
25
+ console.error("");
26
+ throw error;
27
+ }
28
+ };
29
+ }
30
+
31
+ export { measureRouteExecution };
@@ -1,4 +1,4 @@
1
- import { Schema, z } from "zod";
1
+ import { ZodType, z } from "zod";
2
2
 
3
3
  import { ServerError } from "../http/badResponses/serverError";
4
4
  import { UnprocessableEntity } from "../http/badResponses/unprocessableEntity";
@@ -15,7 +15,7 @@ function formatErrorMessage(error: z.ZodError) {
15
15
  return [title, ...lines].join("\n");
16
16
  }
17
17
 
18
- class SchemaValidator<T extends Schema> {
18
+ class SchemaValidator<T extends ZodType> {
19
19
  functionName: string;
20
20
  callerInfo: string;
21
21
 
@@ -29,7 +29,7 @@ class SchemaValidator<T extends Schema> {
29
29
  return this.schema.safeParse(data).success;
30
30
  }
31
31
 
32
- safeValidate(data: any): z.SafeParseReturnType<z.infer<T>, z.infer<T>> {
32
+ safeValidate(data: any): z.ZodSafeParseResult<z.infer<T>> {
33
33
  return this.schema.safeParse(data);
34
34
  }
35
35
 
@@ -59,7 +59,7 @@ class SchemaValidator<T extends Schema> {
59
59
  );
60
60
  }
61
61
 
62
- return formParsed.data;
62
+ return formParsed.data as z.infer<T>;
63
63
  }
64
64
  }
65
65
 
package/tsconfig.json CHANGED
@@ -16,6 +16,6 @@
16
16
  "types": ["bun-types"],
17
17
  "verbatimModuleSyntax": true
18
18
  },
19
- "exclude": ["node_modules", "dist"],
20
- "include": ["src/**/*.ts"]
19
+ "exclude": ["dist", "node_modules", "**/__test__"],
20
+ "include": ["src/**/*.ts", "src/**/*.ts"]
21
21
  }
@@ -1,40 +0,0 @@
1
- type ConfigProps = {
2
- status: number;
3
- method: "POST" | "GET" | "PUT" | "DELETE" | "PATCH" | "ERROR";
4
- request: string;
5
- response: string;
6
- token: string;
7
- };
8
- /**
9
- * Sends a request to the inbox flow API with the provided configuration.
10
- *
11
- * @param config - The configuration object for the request.
12
- * @param config.status - The HTTP status code associated with the request.
13
- * @param config.method - The HTTP method used for the request. Can be "POST", "GET", "PUT", "DELETE", "PATCH", or "ERROR".
14
- * @param config.request - The request payload or details as a string.
15
- * @param config.response - The response payload or details as a string.
16
- * @param config.token - The token associated with the request for authentication or identification.
17
- *
18
- * @remarks
19
- * - This function retrieves the inbox flow configuration using `InboxFlowInstance.getInboxConfig()`.
20
- * - If the configuration is not available, the function will return early without performing any action.
21
- * - In a development environment (`NODE_ENV === "development"`), the function will also return early.
22
- * - The request is sent as a POST request to the inbox API URL with the provided configuration details.
23
- * - If an error occurs during the request, it will be logged using the `httpDebug` service.
24
- *
25
- * @example
26
- * ```typescript
27
- * const config = {
28
- * status: 200,
29
- * method: "POST",
30
- * request: JSON.stringify({ key: "value" }),
31
- * response: JSON.stringify({ success: true }),
32
- * token: "example-token",
33
- * };
34
- *
35
- * await inboxFlowRequest(config);
36
- * ```
37
- */
38
- declare function inboxFlowRequest(config: ConfigProps): Promise<void>;
39
- export { inboxFlowRequest };
40
- //# sourceMappingURL=inboxFlowRequest.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"inboxFlowRequest.d.ts","sourceRoot":"","sources":["../../src/api/inboxFlowRequest.ts"],"names":[],"mappings":"AAGA,KAAK,WAAW,GAAG;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,GAAG,KAAK,GAAG,KAAK,GAAG,QAAQ,GAAG,OAAO,GAAG,OAAO,CAAC;IAC9D,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,iBAAe,gBAAgB,CAAC,MAAM,EAAE,WAAW,iBA+BlD;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
@@ -1,63 +0,0 @@
1
- import { InboxFlowInstance } from "../config/inboxFlowInstance";
2
- import { httpDebug } from "../services/httpDebug";
3
- /**
4
- * Sends a request to the inbox flow API with the provided configuration.
5
- *
6
- * @param config - The configuration object for the request.
7
- * @param config.status - The HTTP status code associated with the request.
8
- * @param config.method - The HTTP method used for the request. Can be "POST", "GET", "PUT", "DELETE", "PATCH", or "ERROR".
9
- * @param config.request - The request payload or details as a string.
10
- * @param config.response - The response payload or details as a string.
11
- * @param config.token - The token associated with the request for authentication or identification.
12
- *
13
- * @remarks
14
- * - This function retrieves the inbox flow configuration using `InboxFlowInstance.getInboxConfig()`.
15
- * - If the configuration is not available, the function will return early without performing any action.
16
- * - In a development environment (`NODE_ENV === "development"`), the function will also return early.
17
- * - The request is sent as a POST request to the inbox API URL with the provided configuration details.
18
- * - If an error occurs during the request, it will be logged using the `httpDebug` service.
19
- *
20
- * @example
21
- * ```typescript
22
- * const config = {
23
- * status: 200,
24
- * method: "POST",
25
- * request: JSON.stringify({ key: "value" }),
26
- * response: JSON.stringify({ success: true }),
27
- * token: "example-token",
28
- * };
29
- *
30
- * await inboxFlowRequest(config);
31
- * ```
32
- */
33
- async function inboxFlowRequest(config) {
34
- const inboxFlowInstance = InboxFlowInstance.getInboxConfig();
35
- if (!inboxFlowInstance)
36
- return;
37
- const { inboxChannelId, inboxUserToken, inboxApiUrl } = inboxFlowInstance;
38
- const { status, method, request, response, token } = config;
39
- if (process.env.NODE_ENV === "development")
40
- return;
41
- try {
42
- const body = JSON.stringify({
43
- status,
44
- channelId: inboxChannelId,
45
- method,
46
- token,
47
- request,
48
- response,
49
- });
50
- await fetch(inboxApiUrl, {
51
- method: "POST",
52
- body,
53
- headers: {
54
- "Content-Type": "application/json",
55
- Authorization: `Bearer ${inboxUserToken}`,
56
- },
57
- });
58
- }
59
- catch (err) {
60
- httpDebug("inboxFlowRequest", "Error sending inbox flow request", err);
61
- }
62
- }
63
- export { inboxFlowRequest };
@@ -1,44 +0,0 @@
1
- type InboxConfigProps = {
2
- inboxChannelId: string;
3
- inboxUserToken: string;
4
- inboxApiUrl: string;
5
- };
6
- type SetInboxConfigProps = {
7
- inboxChannelId: string;
8
- inboxUserToken: string;
9
- inboxApiUrl?: string;
10
- };
11
- /**
12
- * The `InboxFlowInstance` class manages the configuration for the inbox flow.
13
- * It allows you to set and retrieve the inbox configuration, including the channel ID,
14
- * user token, and API URL.
15
- */
16
- declare class InboxFlowInstance {
17
- private static inboxConfig?;
18
- /**
19
- * Sets the configuration for the inbox. This method initializes the inbox configuration
20
- * with the provided `inboxConfig` values. If the configuration has already been set,
21
- * the method will return early without making any changes.
22
- *
23
- * @param inboxConfig - An object containing the inbox configuration properties.
24
- * @param inboxConfig.inboxChannelId - The key used to identify the inbox.
25
- * @param inboxConfig.inboxUserToken - The user token for authenticating with the inbox.
26
- * @param inboxConfig.inboxApiUrl - (Optional) The API URL for the inbox. If not provided,
27
- * a default URL will be used.
28
- */
29
- static setInboxConfig(inboxConfig: SetInboxConfigProps): void;
30
- /**
31
- * Retrieves the current inbox configuration for the InboxFlowInstance.
32
- *
33
- * @returns {InboxConfigProps | undefined} The current inbox configuration if set,
34
- * or `undefined` if no configuration has been initialized.
35
- */
36
- static getInboxConfig(): InboxConfigProps | undefined;
37
- /**
38
- * Resets the inbox configuration to `undefined`.
39
- * This method can be used to clear the current configuration.
40
- */
41
- static resetInboxConfig(): void;
42
- }
43
- export { InboxFlowInstance };
44
- //# sourceMappingURL=inboxFlowInstance.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"inboxFlowInstance.d.ts","sourceRoot":"","sources":["../../src/config/inboxFlowInstance.ts"],"names":[],"mappings":"AAAA,KAAK,gBAAgB,GAAG;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;;;GAIG;AAEH,cAAM,iBAAiB;IACrB,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAmB;IAE9C;;;;;;;;;;OAUG;IAEH,MAAM,CAAC,cAAc,CAAC,WAAW,EAAE,mBAAmB;IAWtD;;;;;OAKG;IACH,MAAM,CAAC,cAAc,IAAI,gBAAgB,GAAG,SAAS;IAIrD;;;OAGG;IAEH,MAAM,CAAC,gBAAgB;CAGxB;AAED,OAAO,EAAE,iBAAiB,EAAE,CAAC"}
@@ -1,46 +0,0 @@
1
- /**
2
- * The `InboxFlowInstance` class manages the configuration for the inbox flow.
3
- * It allows you to set and retrieve the inbox configuration, including the channel ID,
4
- * user token, and API URL.
5
- */
6
- class InboxFlowInstance {
7
- static inboxConfig;
8
- /**
9
- * Sets the configuration for the inbox. This method initializes the inbox configuration
10
- * with the provided `inboxConfig` values. If the configuration has already been set,
11
- * the method will return early without making any changes.
12
- *
13
- * @param inboxConfig - An object containing the inbox configuration properties.
14
- * @param inboxConfig.inboxChannelId - The key used to identify the inbox.
15
- * @param inboxConfig.inboxUserToken - The user token for authenticating with the inbox.
16
- * @param inboxConfig.inboxApiUrl - (Optional) The API URL for the inbox. If not provided,
17
- * a default URL will be used.
18
- */
19
- static setInboxConfig(inboxConfig) {
20
- const defaultInboxURL = `https://logs-inbox-flow-logs.vw6wo7.easypanel.host/api/call`;
21
- if (!!this.inboxConfig)
22
- return;
23
- this.inboxConfig = {
24
- inboxChannelId: inboxConfig.inboxChannelId,
25
- inboxUserToken: inboxConfig.inboxUserToken,
26
- inboxApiUrl: inboxConfig.inboxApiUrl || defaultInboxURL,
27
- };
28
- }
29
- /**
30
- * Retrieves the current inbox configuration for the InboxFlowInstance.
31
- *
32
- * @returns {InboxConfigProps | undefined} The current inbox configuration if set,
33
- * or `undefined` if no configuration has been initialized.
34
- */
35
- static getInboxConfig() {
36
- return this.inboxConfig;
37
- }
38
- /**
39
- * Resets the inbox configuration to `undefined`.
40
- * This method can be used to clear the current configuration.
41
- */
42
- static resetInboxConfig() {
43
- this.inboxConfig = undefined;
44
- }
45
- }
46
- export { InboxFlowInstance };
@@ -1,76 +0,0 @@
1
- import { InboxFlowInstance } from "../config/inboxFlowInstance";
2
- import { httpDebug } from "../services/httpDebug";
3
-
4
- type ConfigProps = {
5
- status: number;
6
- method: "POST" | "GET" | "PUT" | "DELETE" | "PATCH" | "ERROR";
7
- request: string;
8
- response: string;
9
- token: string;
10
- };
11
-
12
- /**
13
- * Sends a request to the inbox flow API with the provided configuration.
14
- *
15
- * @param config - The configuration object for the request.
16
- * @param config.status - The HTTP status code associated with the request.
17
- * @param config.method - The HTTP method used for the request. Can be "POST", "GET", "PUT", "DELETE", "PATCH", or "ERROR".
18
- * @param config.request - The request payload or details as a string.
19
- * @param config.response - The response payload or details as a string.
20
- * @param config.token - The token associated with the request for authentication or identification.
21
- *
22
- * @remarks
23
- * - This function retrieves the inbox flow configuration using `InboxFlowInstance.getInboxConfig()`.
24
- * - If the configuration is not available, the function will return early without performing any action.
25
- * - In a development environment (`NODE_ENV === "development"`), the function will also return early.
26
- * - The request is sent as a POST request to the inbox API URL with the provided configuration details.
27
- * - If an error occurs during the request, it will be logged using the `httpDebug` service.
28
- *
29
- * @example
30
- * ```typescript
31
- * const config = {
32
- * status: 200,
33
- * method: "POST",
34
- * request: JSON.stringify({ key: "value" }),
35
- * response: JSON.stringify({ success: true }),
36
- * token: "example-token",
37
- * };
38
- *
39
- * await inboxFlowRequest(config);
40
- * ```
41
- */
42
-
43
- async function inboxFlowRequest(config: ConfigProps) {
44
- const inboxFlowInstance = InboxFlowInstance.getInboxConfig();
45
- if (!inboxFlowInstance) return;
46
-
47
- const { inboxChannelId, inboxUserToken, inboxApiUrl } = inboxFlowInstance;
48
-
49
- const { status, method, request, response, token } = config;
50
-
51
- if (process.env.NODE_ENV === "development") return;
52
-
53
- try {
54
- const body = JSON.stringify({
55
- status,
56
- channelId: inboxChannelId,
57
- method,
58
- token,
59
- request,
60
- response,
61
- });
62
-
63
- await fetch(inboxApiUrl, {
64
- method: "POST",
65
- body,
66
- headers: {
67
- "Content-Type": "application/json",
68
- Authorization: `Bearer ${inboxUserToken}`,
69
- },
70
- });
71
- } catch (err) {
72
- httpDebug("inboxFlowRequest", "Error sending inbox flow request", err);
73
- }
74
- }
75
-
76
- export { inboxFlowRequest };
@@ -1,65 +0,0 @@
1
- type InboxConfigProps = {
2
- inboxChannelId: string;
3
- inboxUserToken: string;
4
- inboxApiUrl: string;
5
- };
6
-
7
- type SetInboxConfigProps = {
8
- inboxChannelId: string;
9
- inboxUserToken: string;
10
- inboxApiUrl?: string;
11
- };
12
-
13
- /**
14
- * The `InboxFlowInstance` class manages the configuration for the inbox flow.
15
- * It allows you to set and retrieve the inbox configuration, including the channel ID,
16
- * user token, and API URL.
17
- */
18
-
19
- class InboxFlowInstance {
20
- private static inboxConfig?: InboxConfigProps;
21
-
22
- /**
23
- * Sets the configuration for the inbox. This method initializes the inbox configuration
24
- * with the provided `inboxConfig` values. If the configuration has already been set,
25
- * the method will return early without making any changes.
26
- *
27
- * @param inboxConfig - An object containing the inbox configuration properties.
28
- * @param inboxConfig.inboxChannelId - The key used to identify the inbox.
29
- * @param inboxConfig.inboxUserToken - The user token for authenticating with the inbox.
30
- * @param inboxConfig.inboxApiUrl - (Optional) The API URL for the inbox. If not provided,
31
- * a default URL will be used.
32
- */
33
-
34
- static setInboxConfig(inboxConfig: SetInboxConfigProps) {
35
- const defaultInboxURL = `https://logs-inbox-flow-logs.vw6wo7.easypanel.host/api/call`;
36
- if (!!this.inboxConfig) return;
37
-
38
- this.inboxConfig = {
39
- inboxChannelId: inboxConfig.inboxChannelId,
40
- inboxUserToken: inboxConfig.inboxUserToken,
41
- inboxApiUrl: inboxConfig.inboxApiUrl || defaultInboxURL,
42
- };
43
- }
44
-
45
- /**
46
- * Retrieves the current inbox configuration for the InboxFlowInstance.
47
- *
48
- * @returns {InboxConfigProps | undefined} The current inbox configuration if set,
49
- * or `undefined` if no configuration has been initialized.
50
- */
51
- static getInboxConfig(): InboxConfigProps | undefined {
52
- return this.inboxConfig;
53
- }
54
-
55
- /**
56
- * Resets the inbox configuration to `undefined`.
57
- * This method can be used to clear the current configuration.
58
- */
59
-
60
- static resetInboxConfig() {
61
- this.inboxConfig = undefined;
62
- }
63
- }
64
-
65
- export { InboxFlowInstance };