0

I have to add new functionality to add some metadata when the referral variable is not empty. I've made this, but something in me is saying that this could be done simpler.

async createStripeCustomer(user, refferal) {
    if (refferal) {
      return stripe.customers.create({
        email: user.email,
        metadata: {
          userId: user.id,
          referral: refferal,
        },
      });
    } else {
      return stripe.customers.create({
        email: user.email,
        metadata: {
          userId: user.id,
        },
      });
    }
  }
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
jr00n
  • 421
  • 1
  • 6
  • 12

2 Answers2

0

You can reduce the duplication like the code below

async createStripeCustomer(user, refferal) {
  const customer = {
    email: user.email,
    metadata: {
      userId: user.id,
    },
  };

  if (refferal) {
    customer.metadata.refferal = refferal;
  }

  return stripe.customers.create(customer);
}
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
0

From memory of the Stripe API, null values in metadata will not set that variable in the metadata.

So you can just do...

async createStripeCustomer(user, refferal) {
    return stripe.customers.create({
        email: user.email,
        metadata: {
            userId: user.id,
            referral: (refferal ? refferal : null)
        },
    });
}
Jordan
  • 1,390
  • 2
  • 9
  • 24
  • I think the problem with this is JSON data will have `referral` key in metadata – Nick Vu Dec 18 '22 at 16:27
  • JSON data @NickVu? There isn't any JSON here. – Ivar Dec 18 '22 at 16:30
  • these metadata fields will pass to stripe and store as key-value pairs. In this case, it may become `referral:"null"` (`"null"` is a string value) – Nick Vu Dec 18 '22 at 16:36
  • As of 2020, null values act to unset metadata keys, so it ***shouldn't*** set! @Ivar the parameter of `.create()` is json :) – Jordan Dec 18 '22 at 16:36
  • @Jordan No, it is a JavaScript object. [That is not JSON](https://stackoverflow.com/a/2904181). – Ivar Dec 18 '22 at 16:38
  • 1
    Apologies, you're quite right. That's what you get for flipping between languages all evening! – Jordan Dec 18 '22 at 16:40
  • bro @Ivar, you can check this document about how they pass metadata in Stripe https://stripe.com/docs/api/metadata – Nick Vu Dec 18 '22 at 16:41
  • I wasn't aware that you were referring to the payload that this call generates. My apologies @NickVu. – Ivar Dec 18 '22 at 16:47