-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.ts
48 lines (46 loc) · 1.46 KB
/
env.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Custom error class for handling missing environment variables.
*
* @extends {Error}
*/
export class EnvironmentNotFoundError extends Error {
readonly key: string;
/**
* Creates an instance of EnvironmentNotFoundError.
*
* @param {string} key - The key of the missing environment variable.
*/
constructor(key: string) {
super(`Missing environment variable: ${key}`);
this.key = key;
this.name = this.constructor.name;
Error.captureStackTrace?.(this, this.constructor);
}
}
/**
* Checks if an environment variable is set and returns its value.
*
* @param {string} key - The key of the environment variable to check.
* @returns {string} The value of the environment variable.
* @throws {EnvironmentNotFoundError} If the environment variable is not set.
*
* @example
* ```typescript
* import { checkAndGetEnvValue } from '@kikiutils/node/env';
*
* // Assuming the environment variable 'API_KEY' is set
* const apiKey = checkAndGetEnvValue('API_KEY');
* console.log(apiKey); // Output: value of 'API_KEY'
*
* // Assuming the environment variable 'API_KEY' is not set
* try {
* const apiKey = checkAndGetEnvValue('API_KEY');
* } catch (error) {
* console.error(error); // Output: Missing environment variable: API_KEY
* }
* ```
*/
export function checkAndGetEnvValue(key: string) {
if (!process.env[key]) throw new EnvironmentNotFoundError(key);
return process.env[key] as string;
}