Takes in an object describing environment variables and parses them according to the supplied rules. Attempts to read secrets using @synanetics/secrets.
process.env.PORT = '3000';
process.env.SOME_ADDRESS = 'http://example.com';
process.env.STRING = 'Hello!';
process.env.LOWER_CASE_THING = 'lower';
process.env.ENABLE_THING = 'true';
process.env.CONFIG = '{ "some_key": "some_value" }';
process.env.SECRET = 'secret://secret-name';
import processEnvParser from '@synanetics/env-variable-parser';
const result = await processEnvParser({
PORT: {
parser: {
type: 'number', // will return PORT as a number
},
},
SOME_ADDRESS: {
parser: {
type: 'URL', // will return SOME_ADDRESS as a URL
},
},
STRING: {
parser: {
type: 'string', // will return STRING as a string, essentially a passthrough.
},
},
LOWER_CASE_THING: {
parser: (value) => value.toUpperCase(), // will return the supplied value in upper case (i.e. "LOWER")
},
ENABLE_THING: {
parser: {
type: 'boolean', // will return `true`
},
},
CONFIG: {
parser: {
type: 'object', // will return a generic object, by using `JSON.parse` on the supplied string value
},
},
SECRET: {
parser: {
type: 'string', // will look up the secret, whose key is "secret-name" from GCP's Secrets Manager.
},
},
FORGET_ME_NOT: {
required: true,
parser: {
type: 'string',
},
},
DEFAULTED_THING: {
parser: {
type: 'string',
defaultValue: 'foo', // will return 'foo' as a string, because no value was supplied.
},
}
});
console.log(result.success); // `false`, because FORGET_ME_NOT was not set.
console.log(result.errors[0].message); // `Required variable "FORGET_ME_NOT" has not been defined.`
console.log(result.result.DEFAULTED_THING); // `'foo'`, because the `result` property of the returned value is dictionary (`Record<string, any>`) of the parsed variables.