jeudi 19 janvier 2023

Can I save instance-specific functions as environment variables (and should I)?

Each instance of my app has a different policy for paying commission to sales reps. Currently I'm using environment variables such as:

// Client 1
SALES_COMMISSION_BASIS = "PERCENTAGE"
SALES_COMMISSION_PERCENT = 15%

// Client 2
SALES_COMMISSION_BASIS = "FLAT_RATE"
SALES_COMMISSION_AMOUNT = £42

I then have a function that returns the commission calculated according to the basis

const commission = (totalFee) => {
  switch (SALES_COMMISSION_BASIS) {

    case "PERCENTAGE":
      return (totalFee * SALES_COMMISSION_PERCENT)
      break;

    case "FLAT_RATE":
      return (SALES_COMMISSION_AMOUNT)
      break;

  }
} 

I could of course simplify this to always return (totalFee * SALES_COMMISSION_PERCENT + SALES_COMMISSION_AMOUNT) but this would still mean that I am including logic for percent-based commission in a flat-rate client and vice-versa, which is what I am seeking to avoid.

What I'd like to do instead is save the commission function into my environment variables.

// Client 1
SALES_COMMISSION_FUNCTION = "(totalFee) => totalFee * 0.15"

// Client 2
SALES_COMMISSION_FUNCTION = "() => 42"

While none of this is particularly language specific, it's worth noting that I'm working with an Express app in Node JS, and I'm currently using dotenv to store environment variables.

My questions are:

  1. Is saving the function to an environment the correct approach?
  2. How would I implement this in a NodeJS app?

Aucun commentaire:

Enregistrer un commentaire