When initializing an env-var instance with from(), you can provide an extraAccessors object. This allows you to attach custom transformation or validation logic to any variable retrieved from that instance.
Each accessor function must accept at least one argument: value, which is the raw value of the environment variable. Note: Do not assume value is a string.
Accessors can also accept additional arguments, which must be passed explicitly when the accessor is invoked on a variable.
const { from } = require('env-var')
process.env.ADMIN = 'admin@example.com'
const env = from(process.env, {
asEmail: (value, requiredDomain) => {
const split = String(value).split('@')
if (split.length !== 2) {
throw new Error('must contain exactly one "@"')
}
if (requiredDomain && (split[1] !== requiredDomain)) {
throw new Error(`must end with @${requiredDomain}`)
}
return value
}
})
// Usage without extra parameters
let validEmail = env.get('ADMIN').asEmail()
// Usage with an additional parameter
let domainSpecificEmail = env.get('ADMIN').asEmail('example.com')