@synanetics/env-variable-parser
v2.2.0
Published
Parses environment variables into TypeScript types
Readme
@synanetics/env-variable-parser
Takes in an object describing environment variables and parses them according to the supplied rules. Attempts to read secrets using @synanetics/secrets.
Usage
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.Custom parser functions
A custom parser function receives the raw environment value. Unlike the type parsers, it is not passed through resolveVersion, so a secret:// or file:// reference arrives unresolved. A parser that needs the referenced value can be asynchronous and resolve it itself; the returned promise is awaited, and a rejection is recorded in errors.
import { resolveVersion } from '@synanetics/secrets';
process.env.DATABASE_CONNECTION = 'secret://database-connection';
const result = await processEnvParser<{ DATABASE_CONNECTION: string }>({
DATABASE_CONNECTION: {
required: true,
parser: async (value) => {
const connection = await resolveVersion(value ?? '');
if (!connection.startsWith('postgres://')) {
throw new Error('DATABASE_CONNECTION must be a postgres:// URL.');
}
return connection;
},
},
});