-
Notifications
You must be signed in to change notification settings - Fork 0
/
environment.ts
53 lines (42 loc) · 1.23 KB
/
environment.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
49
50
51
52
53
import dotenv from 'dotenv';
import { join } from 'path';
import { existsSync } from 'node:fs';
const modes = ['production', 'development', 'integration'];
type Mode = typeof modes[number];
interface Environment {
mode: Mode;
host: string;
port: number;
}
function getEnvironment(): Environment {
const mode: Mode = process.env.NODE_ENV ?? 'production';
const rootDir = process.cwd();
const envFile = join(rootDir, `.env.${mode}`);
if (existsSync(envFile)) {
dotenv.config({
path: envFile,
debug: mode === 'development',
});
} else {
console.warn(`Cannot find the .env.${mode} file`);
throw new Error('ENVIRONMENT_NOT_FOUND');
}
const port = process.env.PORT as string;
if (!port) {
console.warn(`Cannot load PORT ${mode} variable`);
}
const host = process.env.HOST as string;
if (!host) {
console.warn(`Cannot load HOST ${mode} variable`);
}
if (!modes.includes(mode) || !port || !host) {
throw new Error('ENVIRONMENT_VARIABLE_NOT_FOUND');
}
return {
mode,
host,
port: Number.parseInt(port),
};
}
const environment: Environment = getEnvironment();
export { environment };