1.0.6 • Published 4 months ago

dotenv-constraint v1.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

dotenv-constraint

šŸš€ dotenv-constraint is a lightweight package for validating and enforcing constraints on environment variables in JavaScript. It ensures that required variables are defined and match expected types.

šŸ“¦ Installation

Install the package via npm:

npm install dotenv-constraint

šŸ› ļø Setup

1ļøāƒ£ Create a Schema File

Before using dotenv-constraint, you must create a .env.schema file to define expected environment variables and their types.

Example .env.schema File:

DB_USERNAME=                  # Required
SERVICE=                      # Required
DB_PORT= #number              # Required and must be a number
NB_LICENSE= #optional#number  # Optional and must be a number if provided

šŸ“Œ Schema Rules:

  • Required variable: Any variable without #optional is mandatory.
  • Optional variable: Add #optional to indicate that a variable is not required.
  • Type constraints: Use #number to enforce numeric values.
  • Optional + Type combination: Use #optional#number for variables that can be omitted but must be numeric if defined.

2ļøāƒ£ Create an .env File

Add your environment variables in a .env file:

DB_USERNAME=admin
SERVICE=some_api_key
DB_PORT=5432
NB_LICENSE=50

3ļøāƒ£ Validate Environment Variables

Add the following script to your code to validate environment variables:

ESM (ECMAScript Modules)

import { validateEnv } from 'dotenv-constraint'

CommonJS (Traditional Node.js Modules)

const { validateEnv } = require('dotenv-constraint')

Then, call the function:

const { success, errors } = validateEnv({
  dotenvPath: '.env',
  schemaPath: '.env.schema',
})

if (!success) {
  console.error('āŒ Environment validation failed:', errors)
}

āš™ļø API

validateEnv(config?: { dotenvPath?: string; schemaPath?: string })

  • dotenvPath (optional, default: .env): Path to the .env file containing the environment variables.
  • schemaPath (optional, default: .env.schema): Path to the schema file defining expected variables.

Return Value

If validation fails, the function returns an error object:

{
  success: false,
  errors: [
    {
      variable: "DB_USERNAME"
      code: "empty",
    },
    {
      variable: "DB_PORT",
      code: "invalid_type",
      expected: "number"
    }
  ]
}

Error Handling

If errors are detected, you can stop your application:

if (!success) {
  console.error(errors)
}

šŸ¤ Contributing

Contributions are welcome! Feel free to submit issues or pull requests. šŸ› ļø

šŸ“œ License

MIT

1.0.6

4 months ago

1.0.5

4 months ago

1.0.4

4 months ago

1.0.3

4 months ago

1.0.0

11 months ago