1 回答
TA贡献1836条经验 获得超13个赞
这是一个想法:
const settings = () => ({
environment: process.env.ENVIRONMENT,
port: process.env.PORT,
database: {
host: process.env.DATABASE_HOST,
port: process.env.DATABASE_PORT,
username: 'postgres',
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
},
awsSqsDefaultQueueUrl: process.env.AWS_SQS_DEFAULT_QUEUE_URL,
sqsEndpoint: process.env.SQS_ENDPOINT,
});
function parseEnvSettings() {
// test values
process.env.ENVIRONMENT = "TEST";
const str = settings.toString();
const pattern = /process\.env\.[a-zA-Z0-9_]+/g;
// get your property names
const matches = [...str.match(pattern).values()];
// build your flat settings object
const parsedSettings = {};
matches.forEach(property => {
parsedSettings[property.substr(property.lastIndexOf(".") + 1)] = eval(property);
});
// here you go
console.log(parsedSettings);
}
parseEnvSettings();
产生:
{
ENVIRONMENT: 'TEST',
PORT: undefined,
DATABASE_HOST: undefined,
DATABASE_PORT: undefined,
DATABASE_PASSWORD: undefined,
DATABASE_NAME: undefined,
AWS_SQS_DEFAULT_QUEUE_URL: undefined,
SQS_ENDPOINT: undefined
}
添加回答
举报