|
1
|
import { isObject } from "@medusajs/framework/utils" |
|
2
|
|
|
3
|
export function applyEnvVarsToProcess(env?: Record<any, any>) { |
|
4
|
const previousEnvVars = new Map<string, string | undefined>() |
|
5
|
|
|
6
|
if (isObject(env)) { |
|
7
|
Object.entries(env).forEach(([k, v]) => { |
|
8
|
previousEnvVars.set(k, process.env[k]) |
|
9
|
process.env[k] = v |
|
10
|
}) |
|
11
|
} |
|
12
|
|
|
13
|
return function restoreEnvVars() { |
|
14
|
for (const [key, value] of previousEnvVars) { |
|
15
|
if (value === undefined) { |
|
16
|
delete process.env[key] |
|
17
|
} else { |
|
18
|
process.env[key] = value |
|
19
|
} |
|
20
|
} |
|
21
|
previousEnvVars.clear() |
|
22
|
} |
|
23
|
} |
|
24
|
|
|
25
|
export function formatError(error: unknown): string { |
|
26
|
if (error instanceof Error) { |
|
27
|
const pgError = error as Error & { |
|
28
|
code?: string |
|
29
|
detail?: string |
|
30
|
hint?: string |
|
31
|
where?: string |
|
32
|
cause?: unknown |
|
33
|
} |
|
34
|
|
|
35
|
const aggregatedErrors = (error as AggregateError).errors |
|
36
|
|
|
37
|
return [ |
|
38
|
pgError.message || pgError.name, |
|
39
|
pgError.code && `code: ${pgError.code}`, |
|
40
|
pgError.detail && `detail: ${pgError.detail}`, |
|
41
|
pgError.hint && `hint: ${pgError.hint}`, |
|
42
|
pgError.where && `where: ${pgError.where}`, |
|
43
|
Array.isArray(aggregatedErrors) && |
|
44
|
aggregatedErrors.map((e) => formatError(e)).join("\n"), |
|
45
|
pgError.cause && `caused by: ${formatError(pgError.cause)}`, |
|
46
|
] |
|
47
|
.filter(Boolean) |
|
48
|
.join("\n") |
|
49
|
} |
|
50
|
|
|
51
|
if (typeof error === "string") { |
|
52
|
return error |
|
53
|
} |
|
54
|
|
|
55
|
if (error && typeof error === "object" && "message" in error) { |
|
56
|
const message = (error as { message?: unknown }).message |
|
57
|
if (typeof message === "string" && message.length > 0) { |
|
58
|
return message |
|
59
|
} |
|
60
|
} |
|
61
|
|
|
62
|
return String(error) |
|
63
|
} |
|
64
|
|
|
65
|
/** |
|
66
|
* Execute a function and return a promise that resolves when the function |
|
67
|
* resolves or rejects when the function rejects or the timeout is reached. |
|
68
|
* @param fn - The function to execute. |
|
69
|
* @param timeout - The timeout in milliseconds. |
|
70
|
* @returns A promise that resolves when the function resolves or rejects when the function rejects or the timeout is reached. |
|
71
|
*/ |
|
72
|
export async function execOrTimeout( |
|
73
|
fn: Promise<any> | (() => Promise<void>), |
|
74
|
timeout: number = 5000 |
|
75
|
) { |
|
76
|
const timeoutPromise = new Promise((_, reject) => { |
|
77
|
setTimeout(() => reject(new Error("Timeout")), timeout).unref() |
|
78
|
}) |
|
79
|
|
|
80
|
const fnPromise = typeof fn === "function" ? fn() : fn |
|
81
|
|
|
82
|
return Promise.race([fnPromise, timeoutPromise]) |
|
83
|
} |