fastify / env-schema

Validate your env variable using Ajv and dotenv
MIT License
211 stars 25 forks source link

Does not return value on Interpolation of variables #182

Open lazuee opened 1 month ago

lazuee commented 1 month ago

Prerequisites

Fastify version

4.10.0

Plugin version

No response

Node.js version

20.12.2

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

23H2

Description

import envSchema, { JSONSchemaType } from 'env-schema';

export interface Env {
  DATABASE_USER: string;
  DATABASE_PASSWORD: string;
  DATABASE_HOST: string;
  DATABASE_PORT: number;
  DATABASE_NAME: string;
  DATABASE_URL: string;
}

const schema: JSONSchemaType<Env> = {
  type: 'object',
  required: ['DATABASE_USER', 'DATABASE_PASSWORD', 'DATABASE_HOST', 'DATABASE_PORT', 'DATABASE_NAME', 'DATABASE_URL'
  ],
  properties: {
    DATABASE_USER: {
      type: 'string',
    },
    DATABASE_PASSWORD: {
      type: 'string',
    },
    DATABASE_HOST: {
      type: 'string',
    },
    DATABASE_PORT: {
      type: 'number',
    },
    DATABASE_NAME: {
      type: 'string',
    },
    DATABASE_URL: {
      type: 'string',
    },
  },
};

const env = envSchema({
  dotenv: true,
  schema,
});

console.log(env.DATABASE_URL); // result: mysql://${DATABASE_USER}:${DATABASE_PASSWORD}@${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME}?ssl-mode=REQUIRED
console.log(process.env.DATABASE_URL); // expected result: mysql://root:pass@localhost:3306/db_name?ssl-mode=REQUIRED
DATABASE_USER="root"
DATABASE_PASSWORD="pass"
DATABASE_HOST="localhost"
DATABASE_PORT="3306"
DATABASE_NAME="db_name"
DATABASE_URL="mysql://${DATABASE_USER}:${DATABASE_PASSWORD}@${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME}?ssl-mode=REQUIRED"

Link to code that reproduces the bug

No response

Expected Behavior

No response

Eomm commented 1 month ago

We don't use any additional plugins, you need to add the https://www.npmjs.com/package/dotenv-expand one.

We may implement a plugins option in this plugin as we did for ajv https://fastify.dev/docs/latest/Reference/Validation-and-Serialization/#ajv-plugins but I would not add this dep to our dependancies.

lazuee commented 1 month ago

Thank you for the suggestion. I added the dotenv-expand package, and it's now working properly.