@digitraffic/common 2024.1.24-2 → 2024.1.30-1

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 (206) hide show
  1. package/dist/__test__/api/handler-factory.test.d.mts +1 -0
  2. package/dist/__test__/api/handler-factory.test.mjs +43 -0
  3. package/dist/__test__/api/response.test.d.mts +1 -0
  4. package/dist/__test__/api/response.test.mjs +86 -0
  5. package/dist/__test__/imports.test.d.mts +1 -0
  6. package/dist/__test__/imports.test.mjs +332 -0
  7. package/dist/__test__/marine/id_utils.test.d.mts +1 -0
  8. package/dist/__test__/marine/id_utils.test.mjs +44 -0
  9. package/dist/__test__/promise/promise.test.d.mts +1 -0
  10. package/dist/__test__/promise/promise.test.mjs +130 -0
  11. package/dist/__test__/runtime/dt-logger.test.d.mts +1 -0
  12. package/dist/__test__/runtime/dt-logger.test.mjs +108 -0
  13. package/dist/__test__/secrets/secret-holder.test.d.mts +1 -0
  14. package/dist/__test__/secrets/secret-holder.test.mjs +89 -0
  15. package/dist/__test__/secrets/secret.test.d.mts +1 -0
  16. package/dist/__test__/secrets/secret.test.mjs +42 -0
  17. package/dist/__test__/test/httpserver.test.d.mts +1 -0
  18. package/dist/__test__/test/httpserver.test.mjs +154 -0
  19. package/dist/__test__/types/lambda-response.test.d.mts +1 -0
  20. package/dist/__test__/types/lambda-response.test.mjs +58 -0
  21. package/dist/__test__/utils/date-utils.test.d.mts +1 -0
  22. package/dist/__test__/utils/date-utils.test.mjs +27 -0
  23. package/dist/__test__/utils/geometry.test.d.mts +1 -0
  24. package/dist/__test__/utils/geometry.test.mjs +24 -0
  25. package/dist/__test__/utils/logging.test.d.mts +1 -0
  26. package/dist/__test__/utils/logging.test.mjs +78 -0
  27. package/dist/__test__/utils/utils.test.d.mts +1 -0
  28. package/dist/__test__/utils/utils.test.mjs +43 -0
  29. package/dist/aws/infra/api/handler-factory.mjs +4 -0
  30. package/dist/aws/infra/api/integration.d.mts +2 -2
  31. package/dist/aws/infra/api/integration.mjs +4 -1
  32. package/dist/aws/infra/api/response.d.mts +1 -1
  33. package/dist/aws/infra/api/responses.d.mts +1 -1
  34. package/dist/aws/infra/api/responses.mjs +2 -0
  35. package/dist/aws/infra/api/static-integration.mjs +1 -1
  36. package/dist/aws/infra/canaries/canary-alarm.d.mts +1 -1
  37. package/dist/aws/infra/canaries/canary-alarm.mjs +2 -0
  38. package/dist/aws/infra/canaries/canary-parameters.mjs +1 -1
  39. package/dist/aws/infra/canaries/canary-role.mjs +1 -0
  40. package/dist/aws/infra/canaries/canary.d.mts +2 -2
  41. package/dist/aws/infra/canaries/canary.mjs +2 -0
  42. package/dist/aws/infra/canaries/database-canary.d.mts +2 -2
  43. package/dist/aws/infra/canaries/database-canary.mjs +2 -0
  44. package/dist/aws/infra/canaries/database-checker.d.mts +1 -1
  45. package/dist/aws/infra/canaries/database-checker.mjs +7 -1
  46. package/dist/aws/infra/canaries/url-canary.d.mts +2 -2
  47. package/dist/aws/infra/canaries/url-canary.mjs +3 -0
  48. package/dist/aws/infra/canaries/url-checker.d.mts +1 -1
  49. package/dist/aws/infra/canaries/url-checker.mjs +5 -4
  50. package/dist/aws/infra/documentation.mjs +5 -1
  51. package/dist/aws/infra/import-util.d.mts +1 -1
  52. package/dist/aws/infra/import-util.mjs +4 -3
  53. package/dist/aws/infra/scheduler.mjs +2 -0
  54. package/dist/aws/infra/security-rule.d.mts +1 -1
  55. package/dist/aws/infra/security-rule.mjs +1 -0
  56. package/dist/aws/infra/sqs-integration.d.mts +1 -1
  57. package/dist/aws/infra/sqs-integration.mjs +3 -1
  58. package/dist/aws/infra/sqs-queue.d.mts +1 -1
  59. package/dist/aws/infra/sqs-queue.mjs +2 -1
  60. package/dist/aws/infra/stack/lambda-configs.d.mts +4 -4
  61. package/dist/aws/infra/stack/lambda-configs.mjs +4 -2
  62. package/dist/aws/infra/stack/monitoredfunction.d.mts +3 -3
  63. package/dist/aws/infra/stack/monitoredfunction.mjs +20 -16
  64. package/dist/aws/infra/stack/parameters.mjs +1 -0
  65. package/dist/aws/infra/stack/rest_apis.d.mts +2 -2
  66. package/dist/aws/infra/stack/rest_apis.mjs +6 -1
  67. package/dist/aws/infra/stack/stack-checking-aspect.d.mts +2 -2
  68. package/dist/aws/infra/stack/stack-checking-aspect.mjs +6 -1
  69. package/dist/aws/infra/stack/stack.d.mts +5 -5
  70. package/dist/aws/infra/stack/stack.mjs +9 -0
  71. package/dist/aws/infra/stack/subscription.mjs +4 -0
  72. package/dist/aws/infra/stacks/db-dns-stack.d.mts +1 -1
  73. package/dist/aws/infra/stacks/db-dns-stack.mjs +1 -0
  74. package/dist/aws/infra/stacks/db-proxy-stack.d.mts +3 -3
  75. package/dist/aws/infra/stacks/db-proxy-stack.mjs +4 -2
  76. package/dist/aws/infra/stacks/db-stack.d.mts +3 -3
  77. package/dist/aws/infra/stacks/db-stack.mjs +11 -7
  78. package/dist/aws/infra/stacks/intra-stack-configuration.d.mts +1 -1
  79. package/dist/aws/infra/stacks/network-stack.d.mts +2 -2
  80. package/dist/aws/infra/stacks/network-stack.mjs +8 -0
  81. package/dist/aws/infra/usage-plans.d.mts +1 -1
  82. package/dist/aws/infra/usage-plans.mjs +1 -0
  83. package/dist/aws/runtime/apikey.d.mts +2 -2
  84. package/dist/aws/runtime/apikey.mjs +2 -1
  85. package/dist/aws/runtime/digitraffic-integration-response.d.mts +1 -1
  86. package/dist/aws/runtime/dt-logger.mjs +6 -2
  87. package/dist/aws/runtime/messaging.d.mts +2 -2
  88. package/dist/aws/runtime/s3.d.mts +2 -2
  89. package/dist/aws/runtime/s3.mjs +2 -1
  90. package/dist/aws/runtime/secrets/dbsecret.d.mts +1 -1
  91. package/dist/aws/runtime/secrets/proxy-holder.mjs +1 -0
  92. package/dist/aws/runtime/secrets/rds-holder.mjs +1 -0
  93. package/dist/aws/runtime/secrets/secret-holder.d.mts +1 -1
  94. package/dist/aws/runtime/secrets/secret-holder.mjs +6 -1
  95. package/dist/aws/runtime/secrets/secret.mjs +4 -2
  96. package/dist/aws/types/errors.mjs +1 -0
  97. package/dist/aws/types/lambda-response.mjs +5 -0
  98. package/dist/aws/types/model-with-reference.mjs +1 -1
  99. package/dist/database/cached.d.mts +1 -1
  100. package/dist/database/database.mjs +1 -0
  101. package/dist/database/last-updated.d.mts +1 -1
  102. package/dist/test/db-testutils.d.mts +1 -1
  103. package/dist/test/db-testutils.mjs +1 -1
  104. package/dist/test/httpserver.mjs +7 -3
  105. package/dist/test/secrets-manager.d.mts +1 -1
  106. package/dist/test/secrets-manager.mjs +1 -1
  107. package/dist/test/testutils.mjs +1 -1
  108. package/dist/types/http-error.mjs +1 -0
  109. package/dist/types/nullable.d.mts +1 -1
  110. package/dist/utils/api-model.d.mts +2 -2
  111. package/dist/utils/api-model.mjs +1 -1
  112. package/dist/utils/geojson-types.d.mts +1 -1
  113. package/dist/utils/geojson-types.mjs +4 -2
  114. package/dist/utils/geometry.d.mts +1 -1
  115. package/dist/utils/geometry.mjs +3 -0
  116. package/dist/utils/retry.d.mts +2 -2
  117. package/dist/utils/retry.mjs +2 -2
  118. package/dist/utils/slack.mjs +1 -0
  119. package/dist/utils/utils.d.mts +2 -2
  120. package/package.json +11 -6
  121. package/src/@types/geojson-validation/index.d.mts +0 -4
  122. package/src/aws/infra/api/handler-factory.mts +0 -86
  123. package/src/aws/infra/api/integration.mts +0 -147
  124. package/src/aws/infra/api/response.mts +0 -165
  125. package/src/aws/infra/api/responses.mts +0 -127
  126. package/src/aws/infra/api/static-integration.mts +0 -108
  127. package/src/aws/infra/canaries/Synthetics.d.mts +0 -21
  128. package/src/aws/infra/canaries/canary-alarm.mts +0 -33
  129. package/src/aws/infra/canaries/canary-keys.mts +0 -3
  130. package/src/aws/infra/canaries/canary-parameters.mts +0 -19
  131. package/src/aws/infra/canaries/canary-role.mts +0 -73
  132. package/src/aws/infra/canaries/canary.mts +0 -44
  133. package/src/aws/infra/canaries/database-canary.mts +0 -98
  134. package/src/aws/infra/canaries/database-checker.mts +0 -163
  135. package/src/aws/infra/canaries/url-canary.mts +0 -98
  136. package/src/aws/infra/canaries/url-checker.mts +0 -388
  137. package/src/aws/infra/documentation.mts +0 -142
  138. package/src/aws/infra/import-util.mts +0 -57
  139. package/src/aws/infra/scheduler.mts +0 -59
  140. package/src/aws/infra/security-rule.mts +0 -38
  141. package/src/aws/infra/sqs-integration.mts +0 -106
  142. package/src/aws/infra/sqs-queue.mts +0 -162
  143. package/src/aws/infra/stack/lambda-configs.mts +0 -135
  144. package/src/aws/infra/stack/monitoredfunction.mts +0 -352
  145. package/src/aws/infra/stack/parameters.mts +0 -74
  146. package/src/aws/infra/stack/rest_apis.mts +0 -322
  147. package/src/aws/infra/stack/stack-checking-aspect.mts +0 -233
  148. package/src/aws/infra/stack/stack.mts +0 -144
  149. package/src/aws/infra/stack/subscription.mts +0 -58
  150. package/src/aws/infra/stacks/db-dns-stack.mts +0 -77
  151. package/src/aws/infra/stacks/db-proxy-stack.mts +0 -134
  152. package/src/aws/infra/stacks/db-stack.mts +0 -292
  153. package/src/aws/infra/stacks/intra-stack-configuration.mts +0 -6
  154. package/src/aws/infra/stacks/network-stack.mts +0 -76
  155. package/src/aws/infra/usage-plans.mts +0 -50
  156. package/src/aws/runtime/apikey.mts +0 -9
  157. package/src/aws/runtime/digitraffic-integration-response.mts +0 -35
  158. package/src/aws/runtime/dt-logger-default.mts +0 -11
  159. package/src/aws/runtime/dt-logger.mts +0 -184
  160. package/src/aws/runtime/environment.mts +0 -22
  161. package/src/aws/runtime/messaging.mts +0 -26
  162. package/src/aws/runtime/s3.mts +0 -44
  163. package/src/aws/runtime/secrets/dbsecret.mts +0 -31
  164. package/src/aws/runtime/secrets/node-ttl.d.mts +0 -12
  165. package/src/aws/runtime/secrets/proxy-holder.mts +0 -34
  166. package/src/aws/runtime/secrets/rds-holder.mts +0 -34
  167. package/src/aws/runtime/secrets/secret-holder.mts +0 -106
  168. package/src/aws/runtime/secrets/secret.mts +0 -58
  169. package/src/aws/types/errors.mts +0 -14
  170. package/src/aws/types/lambda-response.mts +0 -100
  171. package/src/aws/types/mediatypes.mts +0 -12
  172. package/src/aws/types/model-with-reference.mts +0 -8
  173. package/src/aws/types/proxytypes.mts +0 -27
  174. package/src/aws/types/tags.mts +0 -3
  175. package/src/database/cached.mts +0 -64
  176. package/src/database/database.mts +0 -107
  177. package/src/database/last-updated.mts +0 -103
  178. package/src/database/models.mts +0 -7
  179. package/src/index.mts +0 -2
  180. package/src/marine/id_utils.mts +0 -30
  181. package/src/marine/rtz.mts +0 -57
  182. package/src/test/asserter.mts +0 -58
  183. package/src/test/db-testutils.mts +0 -52
  184. package/src/test/httpserver.mts +0 -111
  185. package/src/test/secrets-manager.mts +0 -37
  186. package/src/test/testutils.mts +0 -39
  187. package/src/types/async-timeout-error.mts +0 -5
  188. package/src/types/aws-env.mts +0 -3
  189. package/src/types/either.mts +0 -9
  190. package/src/types/http-error.mts +0 -8
  191. package/src/types/input-error.mts +0 -2
  192. package/src/types/language.mts +0 -3
  193. package/src/types/nullable.mts +0 -21
  194. package/src/types/traffictype.mts +0 -8
  195. package/src/types/urn.mts +0 -1
  196. package/src/types/util-types.mts +0 -10
  197. package/src/types/validator.mts +0 -10
  198. package/src/utils/api-model.mts +0 -133
  199. package/src/utils/base64.mts +0 -16
  200. package/src/utils/date-utils.mts +0 -53
  201. package/src/utils/geojson-types.mts +0 -22
  202. package/src/utils/geometry.mts +0 -171
  203. package/src/utils/logging.mts +0 -75
  204. package/src/utils/retry.mts +0 -200
  205. package/src/utils/slack.mts +0 -26
  206. package/src/utils/utils.mts +0 -184
@@ -1,75 +0,0 @@
1
- import { AxiosError } from "axios";
2
- import { DtLogger } from "../aws/runtime/dt-logger.mjs";
3
- import { getEnvVariableOrElse } from "./utils.mjs";
4
-
5
- const functionName = getEnvVariableOrElse("AWS_LAMBDA_FUNCTION_NAME", "test");
6
-
7
- /**
8
- * Curried version of logException.
9
- *
10
- * @example <caption>Using default configuration</caption>
11
- * Promise.reject(x).catch(createExceptionLogger())
12
- *
13
- * @example <caption>Providing external logger and requiring stack</caption>
14
- * import {logger} from "@digitraffic/common/dist/aws/runtime/dt-logger-default"
15
- * Promise.reject(x).catch(createExceptionLogger(logger, true))
16
- *
17
- * @param [logger=undefined] - DtLogger to use. If not given, will create a new instance of DtLogger
18
- * @param [includeStack=false] - Define if the stack trace should be logged.
19
- * @param error - The error instance to be logged.
20
- * @returns Logs the error without rethrowing.
21
- * @see {@link logException}
22
- */
23
- export function createExceptionLogger(
24
- logger: DtLogger | undefined = undefined,
25
- includeStack = false
26
- ) {
27
- let thatLogger: DtLogger;
28
- if (logger) {
29
- thatLogger = logger;
30
- } else {
31
- thatLogger = new DtLogger();
32
- }
33
-
34
- return (error: unknown) => {
35
- logException(thatLogger, error, includeStack);
36
- };
37
- }
38
-
39
- /**
40
- * Log given exception with level ERROR to given logger.
41
- *
42
- * Supports AxiosError, Error and string
43
- *
44
- * @param logger - DtLogger to use
45
- * @param error - AxiosError, Error or string to log
46
- * @param [includeStack=true] - Include stack in the message, default false
47
- * @returns Logs the error without rethrowing
48
- * @see {@link DtLogger.log}
49
- * @see {@link createExceptionLogger} for a curried setup
50
- */
51
- export function logException(
52
- logger: DtLogger,
53
- error: unknown,
54
- includeStack = false
55
- ) {
56
- const message =
57
- error instanceof Error
58
- ? error.message
59
- : typeof error === "string"
60
- ? error
61
- : JSON.stringify(error);
62
-
63
- const stack =
64
- error instanceof Error && includeStack ? error.stack : undefined;
65
-
66
- const customCode = error instanceof AxiosError ? error.code : undefined;
67
-
68
- logger.error({
69
- type: "Error",
70
- method: `${functionName}.logException`,
71
- message,
72
- customCode,
73
- stack,
74
- });
75
- }
@@ -1,200 +0,0 @@
1
- import { HttpError } from "../types/http-error.mjs";
2
- import { AsyncTimeoutError } from "../types/async-timeout-error.mjs";
3
- import { logger } from "../aws/runtime/dt-logger-default.mjs";
4
-
5
- export enum RetryLogError {
6
- LOG_ALL_AS_ERRORS,
7
- LOG_LAST_RETRY_AS_ERROR_OTHERS_AS_WARNS,
8
- NO_LOGGING,
9
- }
10
-
11
- export type TimeoutFn = (retryCount: number) => number;
12
- export type RetryPredicate = (error: unknown) => boolean;
13
-
14
- /**
15
- * Utility timeout functions for "retry" function.
16
- */
17
- export const timeoutFunctions = (function () {
18
- return {
19
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
20
- noTimeout: (retryCount: number): number => {
21
- return 0;
22
- },
23
- exponentialTimeout: (retryCount: number): number => {
24
- return 2 ** retryCount * 1000;
25
- },
26
- };
27
- })();
28
-
29
- /**
30
- * Utility retry predicates for "retry" function.
31
- */
32
- export const retryPredicates = (function () {
33
- const retryStatusCodes = new Set([
34
- // service might return 403 for no apparent reason
35
- 403,
36
- // Opensearch responds 429, if you make too many requests too fast
37
- 429,
38
- ]);
39
- return {
40
- retryBasedOnStatusCode: (error: unknown): boolean => {
41
- if (error instanceof HttpError) {
42
- return retryStatusCodes.has(error.statusCode);
43
- }
44
- return false;
45
- },
46
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
47
- alwaysRetry: (error: unknown): boolean => {
48
- return true;
49
- },
50
- };
51
- })();
52
-
53
- function readPossibleErrorMessage(error: unknown): string {
54
- if (error instanceof Error) {
55
- return error.message;
56
- }
57
- return "Something else than an Error object was thrown";
58
- }
59
-
60
- // Tämä muuttuja on testejä varten määritelty täällä.
61
- export let retryCount = 0;
62
-
63
- async function retryRecursive<T>(
64
- asyncFn: () => Promise<T>,
65
- retries: number,
66
- retryCountInj: number,
67
- logError: RetryLogError,
68
- timeoutBetweenRetries: TimeoutFn,
69
- retryPredicate: RetryPredicate
70
- ): Promise<T> {
71
- const asyncFnTimeout = 30 * 60 * 1000; // 30 minutes
72
- if (!isFinite(retries)) {
73
- throw new Error("Only finite numbers are supported");
74
- }
75
- if (retries > 100) {
76
- throw new Error("Exceeded the maximum retry count of 100");
77
- }
78
- try {
79
- // NOTE, a Promise cannot be cancelled. So if the asyncFn calls multiple async/await paris and the first one takes 31 minutes to complete,
80
- // then the rest of async/await pairs will be called even though AysncTimeoutError is allready thrown.
81
- const result: T = await Promise.race([
82
- asyncFn(),
83
- new Promise<never>((_, reject) =>
84
- setTimeout(
85
- () => reject(new AsyncTimeoutError()),
86
- asyncFnTimeout
87
- )
88
- ),
89
- ]);
90
- return result;
91
- } catch (error) {
92
- const remainingRetries = retries - 1;
93
-
94
- if (logError === RetryLogError.LOG_ALL_AS_ERRORS) {
95
- logger.error({
96
- message: readPossibleErrorMessage(error),
97
- method: "retry.retryRecursive",
98
- });
99
- } else if (
100
- logError === RetryLogError.LOG_LAST_RETRY_AS_ERROR_OTHERS_AS_WARNS
101
- ) {
102
- if (remainingRetries < 0) {
103
- logger.error({
104
- message: readPossibleErrorMessage(error),
105
- method: "retry.retryRecursive",
106
- });
107
- } else {
108
- logger.warn({
109
- message: readPossibleErrorMessage(error),
110
- method: "retry.retryRecursive",
111
- });
112
- }
113
- }
114
-
115
- if (remainingRetries < 0) {
116
- logger.warn({
117
- message: "No retries left",
118
- method: "retry.retryRecursive",
119
- });
120
- throw new Error("No retries left");
121
- }
122
- logger.warn({
123
- message: `Retrying with remaining retries ${remainingRetries}`,
124
- method: "retry.retryRecursive",
125
- });
126
- if (retryPredicate(error)) {
127
- retryCountInj++;
128
- retryCount = retryCountInj;
129
- const milliseconds = timeoutBetweenRetries(retryCountInj);
130
- if (milliseconds > 0) {
131
- await new Promise((resolve) =>
132
- setTimeout(resolve, milliseconds)
133
- );
134
- }
135
- return retryRecursive(
136
- asyncFn,
137
- remainingRetries,
138
- retryCountInj,
139
- logError,
140
- timeoutBetweenRetries,
141
- retryPredicate
142
- );
143
- } else {
144
- throw new Error("Retry predicate failed");
145
- }
146
- }
147
- }
148
-
149
- /**
150
- * Utility function for retrying async functions.
151
- * @param asyncFn Function
152
- * @param retries Amount of retries, default is 3. If set to <= 0, no retries will be done. Using non-finite numbers will throw an error. The maximum allowed retry count is 100.
153
- * @param logError Logging options
154
- * @param timeoutBetweenRetries A function that returns the timeout between retries in milliseconds. Default is a function returning 0. The function is called with the current retry count.
155
- * @param retryPredicate A function that returns true if the error should be retried. Default is a function that always returns true. The function is called with the error object.
156
- * @return Promise return value
157
- */
158
- export async function retry<T>(
159
- asyncFn: () => Promise<T>,
160
- retries = 3,
161
- logError = RetryLogError.LOG_LAST_RETRY_AS_ERROR_OTHERS_AS_WARNS,
162
- timeoutBetweenRetries: TimeoutFn = timeoutFunctions.noTimeout,
163
- retryPredicate: RetryPredicate = retryPredicates.alwaysRetry
164
- ): Promise<T> {
165
- retryCount = 0;
166
-
167
- logger.debug({
168
- message: `Retrying with ${retries} retries`,
169
- method: "retry.retry",
170
- });
171
- return retryRecursive(
172
- asyncFn,
173
- retries,
174
- 0,
175
- logError,
176
- timeoutBetweenRetries,
177
- retryPredicate
178
- );
179
- }
180
-
181
- function wrapArgsToFn<T>(
182
- fn: (...args: unknown[]) => Promise<T>,
183
- ...args: unknown[]
184
- ): () => Promise<T> {
185
- return async () => await fn(...args);
186
- }
187
-
188
- export async function retryRequest<T>(
189
- request: (...args: unknown[]) => Promise<T>,
190
- ...args: unknown[]
191
- ): Promise<T> {
192
- const asyncFn = wrapArgsToFn(request, ...args);
193
- return retry(
194
- asyncFn,
195
- 5,
196
- RetryLogError.LOG_LAST_RETRY_AS_ERROR_OTHERS_AS_WARNS,
197
- timeoutFunctions.exponentialTimeout,
198
- retryPredicates.retryBasedOnStatusCode
199
- );
200
- }
@@ -1,26 +0,0 @@
1
- import axios from "axios";
2
- import { logger } from "../aws/runtime/dt-logger-default.mjs";
3
- import { logException } from "./logging.mjs";
4
-
5
- export class SlackApi {
6
- private readonly url: string;
7
-
8
- constructor(url: string) {
9
- this.url = url;
10
- }
11
-
12
- async notify(text: string) {
13
- try {
14
- logger.info({
15
- method: "SlackApi.notify",
16
- message: "Sending slack notification",
17
- });
18
-
19
- await axios.post(this.url, {
20
- text,
21
- });
22
- } catch (error) {
23
- logException(logger, error);
24
- }
25
- }
26
- }
@@ -1,184 +0,0 @@
1
- import { AwsEnv } from "../types/aws-env.mjs";
2
- import { Either } from "../types/either.mjs";
3
- import { EnvKeys } from "../aws/runtime/environment.mjs";
4
-
5
- /**
6
- * Check if arrays have only elements that also exists also in other array.
7
- * Individual element count doesn't matter.
8
- * Function works only for primitive types and for other it just checks the reference to object.
9
- *
10
- * Some examples
11
- * bothArraysHasSameValues( [a, b], [b, a] ) => true
12
- * bothArraysHasSameValues( [a, a], [a, a, a] ) => true
13
- * bothArraysHasSameValues( [a, b], [a] ) => false
14
- *
15
- * Object references:
16
- * const o1 = { a: 1, b: 2};
17
- * const o2 = { a: 1, b: 2};
18
- * // Arrays has references to same objects
19
- * bothArraysHasSameValues([o1], [o1])) => true
20
- * Arrays have references to different objects
21
- * bothArraysHasSameValues([o1], [o2])) => false
22
- *
23
- * @param a first array to compare
24
- * @param b second array to compare
25
- */
26
- export function bothArraysHasSameValues(
27
- a: null | undefined | unknown[],
28
- b: null | undefined | unknown[]
29
- ): boolean {
30
- if ((a && !b) || (!a && b)) {
31
- return false;
32
- } else if (!a && !b) {
33
- return true;
34
- }
35
- const aSet = new Set(a);
36
- const bSet = new Set(b);
37
- if (aSet.size !== bSet.size) {
38
- return false;
39
- }
40
- return Array.from(aSet).every((value) => bSet.has(value));
41
- }
42
-
43
- /**
44
- * Returns the last item on the array. If the array is empty, throws an error!
45
- */
46
- export function getLast<T>(array: T[], sortFunction?: (a: T) => number): T {
47
- return getFirstOrLast(false, array, sortFunction);
48
- }
49
-
50
- /**
51
- * Returns the first item on the array. If the array is empty, throws an error!
52
- */
53
- export function getFirst<T>(array: T[], sortFunction?: (a: T) => number): T {
54
- return getFirstOrLast(true, array, sortFunction);
55
- }
56
-
57
- function getFirstOrLast<T>(
58
- getFirst: boolean,
59
- array: T[],
60
- sortFunction?: (a: T) => number
61
- ): T {
62
- if (array.length == 0) {
63
- throw new Error(
64
- `can't get ${getFirst ? "first" : "last"} from empty array!`
65
- );
66
- }
67
-
68
- const index = getFirst ? 0 : array.length - 1;
69
-
70
- if (sortFunction) {
71
- return array.sort(sortFunction)[index];
72
- }
73
-
74
- return array[index];
75
- }
76
-
77
- /**
78
- * Gets basic AWS environment variables. Throws error if variables are not found.
79
- *
80
- * @param key Environment key
81
- * @return string
82
- * @See https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html
83
- */
84
- export function getAwsEnv(): AwsEnv {
85
- return {
86
- region: getEnvVariable("AWS_REGION"),
87
- };
88
- }
89
-
90
- /**
91
- * Gets environment variable. Throws error if variable is not found.
92
- *
93
- * @param key Environment key
94
- * @return string
95
- */
96
- export function getEnvVariable(key: string): string {
97
- const either = getEnvVariableSafe(key);
98
- if (either.result === "error") {
99
- throw new Error(either.message);
100
- }
101
- return either.value;
102
- }
103
-
104
- /**
105
- * Gets environment variable. Safe version returns object with either ok or error status.
106
- * Easier to use for recovery than catching an error.
107
- *
108
- * @param key Environment key
109
- * @return Either<string>
110
- */
111
- export function getEnvVariableSafe(key: string): Either<string> {
112
- const value = process.env[key];
113
- if (value === undefined) {
114
- return {
115
- result: "error",
116
- message: `Error: environment variable "${key}" is undefined.`,
117
- };
118
- }
119
- return { result: "ok", value };
120
- }
121
-
122
- /**
123
- * Sets environment variable.
124
- *
125
- * @param key Environment key
126
- * @param value Environment variable value
127
- */
128
- export function setEnvVariable(key: string, value: string) {
129
- process.env[key] = value;
130
- }
131
-
132
- /**
133
- * Gets environment variable. If environment variable is undefined, returns value of given function.
134
- *
135
- * @param key Environment key
136
- * @param fn Alternative function
137
- */
138
- export function getEnvVariableOr<T>(key: string, fn: () => T): string | T {
139
- const either = getEnvVariableSafe(key);
140
- if (either.result === "ok") {
141
- return either.value;
142
- }
143
- return fn();
144
- }
145
-
146
- /**
147
- * Gets environment variable. If environment variable is undefined, returns given value.
148
- * Use to return an explicit alternative value e.g. in cases where environment variable may be undefined.
149
- *
150
- * @param key Environment key
151
- * @param orElse Alternative value
152
- */
153
- export function getEnvVariableOrElse<T>(key: string, orElse: T): string | T {
154
- return getEnvVariableOr(key, () => orElse);
155
- }
156
-
157
- export function setSecretOverideAwsRegionEnv(region: string) {
158
- setEnvVariable(EnvKeys.SECRET_OVERRIDE_AWS_REGION, region);
159
- }
160
-
161
- /**
162
- * ESLint won't allow to call Object.prototype builtin methods.
163
- * To call hasOwnProperty we must use Object.prototype.hasOwnProperty.call()
164
- * @param object to test for property
165
- * @param propertyName property name to check
166
- * @see https://eslint.org/docs/latest/rules/no-prototype-builtins
167
- */
168
- export function hasOwnPropertySafe(
169
- object: object,
170
- propertyName: string
171
- ): boolean {
172
- return Object.prototype.hasOwnProperty.call(object, propertyName);
173
- }
174
-
175
- /**
176
- * Return an error message from the given object hat might be an Error object.
177
- * @param maybeError
178
- */
179
- export function getErrorMessage(maybeError: unknown) {
180
- if (maybeError instanceof Error) {
181
- return maybeError.name + ": " + maybeError.message;
182
- }
183
- return String(maybeError);
184
- }