Skip to content
This repository has been archived by the owner on Feb 17, 2023. It is now read-only.

Parsing numbers, booleans and null values #36

Closed
wjstraver opened this issue Aug 6, 2020 · 3 comments
Closed

Parsing numbers, booleans and null values #36

wjstraver opened this issue Aug 6, 2020 · 3 comments

Comments

@wjstraver
Copy link

Hi,

First off, I like how easy it is with this package to import .env values into my project. However, I've noticed in my test projects, I'll would like it if true/false are parsed as boolean, numbers are correctly parsed, empty values are null or undefined instead of an empty string.

Right now I add the following code to my projects:

import {config} from "https://deno.land/x/dotenv@v0.5.0/mod.ts";

type EnvValue = null|number|boolean|string

type EnvObject = {
    [key: string]: EnvValue
}

export const env = Object.entries(config())
    .reduce((envObj: EnvObject, [key, value]: [string, string]) => {
        if(value === "" || value === "null") {
            envObj[key] = null;
        } else if (/^true|false$/i.test(value)) {
            envObj[key] = JSON.parse(value.toLowerCase());
        } else if (/^(\d*\.?\d+)$/.test(value)) {
            envObj[key] = parseFloat(value);
        } else {
            envObj[key] = value;
        }

        return envObj;
    }, {});

How would you look at the idea of implementing this something along the line of:

config({parseTypes: true});
@pietvanzoen
Copy link
Owner

Hi there! Thanks for the kind words. Apologies for the delayed reply.

This is an interesting idea and something people have mentioned before.

The tricky thing to get around is that as far as the shell is concerned environment variables are always strings. Deno.env.set respects this and will error if given anything but a string. So the export option of config would be incompatible with the parseTypes option. I'd rather keep things consistent between how config() returns variables and how Deno.env.get returns variables.

However, if you'd like to publish a helper module with what you have (similar to dotenv-expand) I'd be happy to include it in the docs.

@wjstraver
Copy link
Author

Hi,

I understand why you would like to stay true to the environment variables by keeping everyting as strings. I'll take a look in creating a helper module myself. Maybe adding something like getEnv('ENV_NAME', 'default value') or other small features as well.

Will let you know when/if I have something!

@pietvanzoen
Copy link
Owner

Doing some housekeeping and closing this issue. Feel free to comment if you have any updates.

Cheers

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants