2023-03-15 06:42:14 +03:00
|
|
|
/** @file Shared utility functions. */
|
|
|
|
import * as fs from 'node:fs'
|
|
|
|
import * as path from 'node:path'
|
2023-03-16 16:09:31 +03:00
|
|
|
import process from 'node:process'
|
2022-08-10 04:41:44 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the environment variable value.
|
|
|
|
*
|
2023-03-15 06:42:14 +03:00
|
|
|
* @param name - The name of the environment variable.
|
|
|
|
* @returns The value of the environment variable.
|
2022-08-10 04:41:44 +03:00
|
|
|
* @throws {Error} If the environment variable is not set.
|
|
|
|
*/
|
2023-03-15 06:42:14 +03:00
|
|
|
export function requireEnv(name: string) {
|
2022-08-10 04:41:44 +03:00
|
|
|
return (
|
|
|
|
process.env[name] ??
|
|
|
|
(() => {
|
|
|
|
throw Error(`Missing ${name} environment variable.`)
|
|
|
|
})()
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Read the path from environment variable and resolve it.
|
|
|
|
*
|
2023-03-15 06:42:14 +03:00
|
|
|
* @param name - The name of the environment variable.
|
|
|
|
* @returns The resolved path.
|
2022-08-10 04:41:44 +03:00
|
|
|
* @throws {Error} If the environment variable is not set.
|
|
|
|
*/
|
2023-03-15 06:42:14 +03:00
|
|
|
export function requireEnvResolvedPath(name: string) {
|
|
|
|
return path.resolve(requireEnv(name))
|
2022-08-10 04:41:44 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Read the path from environment variable and resolve it. Verify that it exists.
|
|
|
|
*
|
2023-03-15 06:42:14 +03:00
|
|
|
* @param name - The name of the environment variable.
|
|
|
|
* @returns The resolved path.
|
2022-08-10 04:41:44 +03:00
|
|
|
* @throws {Error} If the environment variable is not set or path does not exist.
|
|
|
|
*/
|
2023-03-15 06:42:14 +03:00
|
|
|
export function requireEnvPathExist(name: string) {
|
|
|
|
const value = requireEnv(name)
|
2023-03-20 12:35:16 +03:00
|
|
|
if (fs.existsSync(value)) {
|
|
|
|
return value
|
|
|
|
} else {
|
|
|
|
throw Error(`File with path ${value} read from environment variable ${name} is missing.`)
|
|
|
|
}
|
2022-08-10 04:41:44 +03:00
|
|
|
}
|