Giter Site home page Giter Site logo

Feature request: Safe getter. about envalid HOT 8 CLOSED

af avatar af commented on July 23, 2024
Feature request: Safe getter.

from envalid.

Comments (8)

af avatar af commented on July 23, 2024

If you misspell the key in your config, you're going to get a validation error by default, right? Unless the env var is also misspelled, which seems unlikely.

As for the second part, check out the transformer option (I replied to your other issue suggesting it just as you posted this :). I think it'll give you the flexibility to do what you're looking for.

from envalid.

einnjo avatar einnjo commented on July 23, 2024

If you misspell the key in your config, you're going to get a validation error by default, right? Unless the env var is also misspelled, which seems unlikely.

Currently a validation error will only be thrown if the variable is mispelled inside the cleanEnv definition. If the variable is misspelled throughout the usage inside the app use(env.misspelled), no error will be thrown and that's what worries me.

As for the second part, check out the transformer option (I replied to your other issue suggesting it just as you posted this :). I think it'll give you the flexibility to do what you're looking for.

Absolutely, I retract the second part entirely.

from envalid.

af avatar af commented on July 23, 2024

Ah I see, I misunderstood the question. Typos in the app could definitely be a source of errors and confusion.

I'm not sure about baking a solution into envalid at this time, but a good approach if you want to throw would be to wrap the cleaned env object in an ES6 proxy. Then you can throw an error (using the get trap) if the desired key isn't present on the cleaned object.

from envalid.

einnjo avatar einnjo commented on July 23, 2024

Yep, it's hard to make typos in cleanEnv since you only type it in one place, but var usage is spread everywhere and constantly changes so it's easier to make a typo there.

It's so easy to implement that I debated whether to open up an issue. But I figured that it could help other people from making the mistakes I did, I also thought that a library that dealt with validating the environment could also validate references to it.

I'll look into the proxies, I'm currently doing this on all of my projects:

// config.js
const envalid = require('envalid');
const { str, email, bool, num, url } = envalid;

const env = envalid.cleanEnv(
    process.env,
    {
        // ... Declare config variables.
    }
);

function get(key) {
    if (env.hasOwnProperty(key)) {
        return env[key];
    }

    throw new Error('Missing config key: ' + key);
}

module.exports = { get };

// Elsewhere...
const Config = require('./config');

getApiResponse(Config.get('API_ERL')); // Throws, should be URL

Anyways, thanks for the great libary and fast responses 👍

from envalid.

af avatar af commented on July 23, 2024

Yeah it's a very valid point. I'll mull it over for a bit and consider adding a proxy wrapper by default. Thanks for the feedback!

from envalid.

SimenB avatar SimenB commented on July 23, 2024

We use a proxy at work as well.

function makeImmutable (mutable) {
    return new Proxy(mutable, {
        get (target, name) {
            // These two checks are needed because calling console.log on a
            // proxy that throws crashes the entire process. This whitelists
            // the necessary properties for `console.log(config)` to work.
            if (['inspect', Symbol.toStringTag].includes(name)) {
                return mutable[name];
            }
            if (name.toString() === 'Symbol(util.inspect.custom)') {
                return mutable[name];
            }

            const val = mutable[name];
            if (val === undefined) {
                throw new Error(`Config key not found: ${name}`);
            } else {
                return val;
            }
        },

        set (name) {
            throw new Error(`Config values can not be changed: ${name}`);
        },
    });
}

(should probably use hasOwnProperty )

from envalid.

af avatar af commented on July 23, 2024

Cool, thanks for the example @SimenB. Any other gotchas you're aware of that would preclude including a proxy wrapper by default when the strict option is set?

from envalid.

SimenB avatar SimenB commented on July 23, 2024

Nah. We've been using that code in production for close to a year without issues

from envalid.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.