1

Here in the below switch-case condition it is throwing error
Cannot read property 'entity' of undefined because for every other case except "paytm" the entity is present in the "payload" but for paytm its "payload_data" --> body.data.payload_data.entity.channel How to solve this issue.

switch(body.data.payload.entity.channel){
            case "paytm"  : 
                await paytm(body);
                break;
            case "phonePe" : 
                await phonePe(body);
                break;    
            case "googlePay":
            default:
                await googlePay(body);
        }

I tried adding multiple things but it didnt worked for me.

Grismak
  • 192
  • 16
  • Why not just fix the data? – Andy Jan 25 '23 at 07:27
  • `const channel = body.data.payload?.entity?.channel ?? body.data.payload_data?.entity?.channel`. And then `swtich(channel)` – adiga Jan 25 '23 at 07:28
  • Or if you are okay with putting `payload_data` to `payload` property: `body.data.payload ??= body.data.payload_data?` – adiga Jan 25 '23 at 07:30

2 Answers2

0

Use optional chain operator

  const targetChannel =
    body?.data?.payload?.entity?.channel ||
    body.data.payload_data.entity.channel;
  switch (targetChannel) {
    case "paytm":
      await paytm(body);
      break;
    case "phonePe":
      await phonePe(body);
      break;
    case "googlePay":
    default:
      await googlePay(body);
  }
Hend El-Sahli
  • 6,268
  • 2
  • 25
  • 42
0

You can use the nullish coalescing operator (??) to ensure that if the payload property is not present, then the payload_data property is used instead:

You can repeatedly press the "Run code snippet" button below to see randomized results in the console.

<script type="module">

function simulateRandomBody () {
  const channel = Math.random() < 0.5 ? "phonePe" : "googlePay";
  return Math.random() < 0.5
    ? { data: { payload: { entity: { channel } } } }
    : { data: { payload_data: { entity: { channel: "paytm" } } } };
}

const paytm = console.log.bind(console);
const phonePe = console.log.bind(console);
const googlePay = console.log.bind(console);

const body = simulateRandomBody();

switch ((body.data.payload ?? body.data.payload_data).entity.channel) {
  case "paytm":
    await paytm(body);
    break;
  case "phonePe":
    await phonePe(body);
    break;
  case "googlePay":
  default:
    await googlePay(body);
}


</script>
jsejcksn
  • 27,667
  • 4
  • 38
  • 62