-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.helper.ts
More file actions
167 lines (139 loc) · 5.62 KB
/
Copy pathconfig.helper.ts
File metadata and controls
167 lines (139 loc) · 5.62 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import dotenv from 'dotenv';
import fs from 'fs';
import Joi from 'joi';
import { ApplicationConfig, Config } from './config.interface';
import config from './config';
export function loadConfig() {
// Determine which env file to load. Precedence:
// 1. Explicit ENV_FILE var
// 2. NODE_ENV=local|development -> .env.local (if exists)
// 3. Fallback to .env
const explicit = process.env.ENV_FILE;
const nodeEnv = (process.env.NODE_ENV || '').toLowerCase();
const candidates: string[] = [];
if (explicit) {
candidates.push(explicit);
} else if (['local', 'development', 'dev'].includes(nodeEnv)) {
candidates.push('.env.local');
}
candidates.push('.env');
let pickedPath = '.env';
for (const c of candidates) {
if (fs.existsSync(c)) {
pickedPath = c;
break;
}
}
let file = Buffer.from('');
try {
file = fs.readFileSync(pickedPath);
} catch {
// If nothing found we proceed with empty buffer relying on process.env
}
const dotenvConfig = dotenv.parse(file);
// Inject parsed values into process.env. Values from the selected env file
// OVERRIDE existing process.env values to ensure .env.local takes precedence
// over .env (which Prisma/dotenv may have auto-loaded).
for (const [k, v] of Object.entries(dotenvConfig)) {
process.env[k] = v;
}
if (!process.env.ENV_FILE_LOGGED) {
// Single log guard to avoid spamming on hot-reload
console.log(`[config] Loaded environment file: ${pickedPath}`);
process.env.ENV_FILE_LOGGED = 'true';
}
// Parse nested JSON in file and merge with process.env
const parsedConfig = parseNestedJson({
...dotenvConfig,
...process.env,
...config(),
});
// Validate the config
return validateConfig(parsedConfig);
}
/**
* Parses environment variable JSON strings into JS objects
*/
function parseNestedJson(config: any): ApplicationConfig {
// Only parse values that are JSON objects or arrays. We avoid
// coercing simple primitives like numbers or booleans that happen
// to be valid JSON (e.g. "1.0") because env vars are expected to
// remain strings unless explicitly JSON objects/arrays.
const initial = { ...config };
return Object.keys(initial).reduce((accumulator, configKey) => {
const raw = initial[configKey];
if (typeof raw !== 'string') return accumulator;
try {
const parsed = JSON.parse(raw);
// Only replace when parsing yields an object or array
if (parsed !== null && (typeof parsed === 'object' || Array.isArray(parsed))) {
accumulator[configKey] = parsed;
}
} catch {
// leave original string value
}
return accumulator;
}, initial) as ApplicationConfig;
}
/**
* Ensures all needed variables are set, and returns the validated JavaScript object
* including the applied default values.
*/
function validateConfig(envConfig: object): ApplicationConfig {
const validatedConfig: ApplicationConfig = { ...envConfig } as ApplicationConfig;
// Validate REDIS_SERVERS as JSON
if (typeof validatedConfig.REDIS_SERVERS === 'string') {
try {
validatedConfig.REDIS_SERVERS = JSON.parse(validatedConfig.REDIS_SERVERS);
} catch (error) {
throw new Error(`Config validation error: REDIS_SERVERS must be a valid JSON string`);
}
}
// Ensure REDIS_SERVERS is an object after parsing
if (typeof validatedConfig.REDIS_SERVERS !== 'object' || validatedConfig.REDIS_SERVERS === null) {
throw new Error(`Config validation error: REDIS_SERVERS must be a valid object`);
}
const envVarsSchema: Joi.ObjectSchema<ApplicationConfig> = Joi.object<ApplicationConfig>({
SERVICE_NAME: Joi.string().required(),
SERVICE_VERSION: Joi.string().required(),
SERVICE_ENVIRONMENT: Joi.string().default('DEVELOPMENT'),
PORT: Joi.number().min(1024).required(),
NODE_ENV: Joi.string().default('local'),
DATABASE_URL: Joi.string().required(),
MONGO_DATABASE_URL: Joi.string().required(),
LOG_ELASTICSEARCH_NODE: Joi.string(),
S3_REGION: Joi.string().required(),
S3_ACCESS_KEY_ID: Joi.string().required(),
S3_SECRET_ACCESS_KEY: Joi.string().required(),
S3_BASE_ENDPOINT: Joi.string().required(),
S3_USER_BUCKET: Joi.string().required(),
QUEUE_REDIS_HOST: Joi.string().required(),
QUEUE_REDIS_PASSWORD: Joi.string(),
QUEUE_REDIS_PORT: Joi.number().required(),
QUEUE_REDIS_USE_TLS: Joi.boolean().default(false),
QUEUE_RETRY_INTERVAL: Joi.number().default(5000),
SMARTCHAIN_RPC_HOST: Joi.string().default('https://explorer-api.devnet.solana.com'),
OPEN_TELEMETRY_ZIPKIN_ENABLED: Joi.boolean().default(false),
OPEN_TELEMETRY_PROMETHEUS_ENABLED: Joi.boolean().default(false),
OPEN_TELEMETRY_COLLECTOR_URL: Joi.string().uri(),
OPEN_TELEMETRY_LIGHTSTEP_ACCESS_TOKEN: Joi.string(),
JWT_ACCESS_SECRET: Joi.string().default('secretkey'),
JWT_EXPIRATION_TIME: Joi.string().default('60m'),
JWT_REFRESH_TOKEN_SECRET: Joi.string().default('refreshTokenSecretkey'),
JWT_REFRESH_EXPIRATION_TIME: Joi.string().default('60m'),
EDGE_KV_URL: Joi.string().default('https://edge-kv-dexcelerate.workers.dev'),
EDGE_KV_AUTHORIZATION_TOKEN: Joi.string().default(''),
REDIS_SERVERS: Joi.object().required(), // Validate as an object
STRIPE_PUBLISHABLE_KEY: Joi.string().allow(''),
STRIPE_SECRET_KEY: Joi.string().allow(''),
STRIPE_WEBHOOK_SECRET: Joi.string().allow(''),
STRIPE_DEFAULT_CURRENCY: Joi.string().length(3).default('usd'),
});
const { error, value: configValue } = envVarsSchema.validate(validatedConfig, {
allowUnknown: true,
});
if (error) {
throw new Error(`Config validation error: ${error.message}`);
}
return configValue;
}