@pitininja/envious
v6.1.5
Published
[](https://badge.fury.io/js/@pitininja%2Fenvious)
Readme
Envious
Parse and validate environment variables
Install
Envious works by installing and using two packages : the core package and a resolver.
Core package
npm i @pitininja/enviousResolvers
Typebox
npm i @pitininja/envious-typeboxYup
npm i @pitininja/envious-yupZod
npm i @pitininja/envious-zodUsage
Here is an example using the Typebox resolver :
import { envious } from '@pitininja/envious';
import { typeboxResolver } from '@pitininja/envious-typebox';
import { Type } from '@sinclair/typebox';
const env = envious({
resolver: typeboxResolver({
schema: Type.Object({
STRING_VAR: Type.String(),
NUMBER_VAR: Type.Integer(),
BOOLEAN_VAR_WITH_DEFAULT: Type.Boolean({ default: false }),
OPTIONAL_VAR: Type.Optional(Type.String())
})
})
});Then run the script with loaded environment variables, and these variables will be parsed and validated.
# Example loading environment variables with Node.js
node --env-file=.env index.js
# Example loading environment variables with TSX
tsx --env-file=.env index.ts
# Example loading environment variables with DotEnv
dotenv -e .env -- node index.jsOptions
Logging
In addition to throwing an EnviousError, errors can be logged in the console. To do so, use the logErrors option :
import { envious } from '@pitininja/envious';
import { typeboxResolver } from '@pitininja/envious-typebox';
import { Type } from '@sinclair/typebox';
const env = envious({
resolver: typeboxResolver({
schema: Type.Object({
STRING_VAR: Type.String()
})
}),
logErrors: true
});You can also provide your own logging function :
import { envious } from '@pitininja/envious';
import { typeboxResolver } from '@pitininja/envious-typebox';
import { Type } from '@sinclair/typebox';
const env = envious({
resolver: typeboxResolver({
schema: Type.Object({
STRING_VAR: Type.String()
})
}),
logErrors: true,
logger: (message) => {
myCustomLogger(message)
}
});Errors
If something goes wrong, Envious will throw an error of class EnviousError.
An EnviousError error contains a message and a list of EnviousErrorVariable.
Here is a simple example of how to handle Envious errors :
import { envious, EnviousError } from '@pitininja/envious';
import { typeboxResolver } from '@pitininja/envious-typebox';
import { Type } from '@sinclair/typebox';
try {
const env = envious({
resolver: typeboxResolver({
schema: Type.Object({
STRING_VAR: Type.String()
})
})
});
} catch (err: unknown) {
if (err instanceof EnviousError) {
// General error message
console.log('Message:', err.message);
// Array of EnviousErrorVariable
console.log('Errors:', err.errors);
for (const { name, messages } of err.errors) {
// Variable name and error messages related to that variable
console.log(`${name} : ${messages.join(', ')}`);
}
}
}