0

Currently, I am attempting to send a payload to an endpoint with node-fetch. I am using the NestJS event emitter and when the event happens sometimes the payload just wont send. So if webhookResponse is undefined after execution is run I want to try the fetch again x number of times before logging an error that it didn't send. I also want to be sure to set a timeout before executing the retry to make sure we wait for that response. How do I do that?

// emitting the event
try {
      await this.mapToWebHookModel(webhookPayload, data);
      this.eventEmitter.emit(
        'deliveryEvent',
        new SomeWebhook(webhookPayload),
        data,
      );
      return 'Webhook Updated';
    } catch (err) {
      console.log(err);
    }
  }

  // Action on event

  @OnEvent('deliveryEvent')
  async findWebhooksAndSend(someWebhook: Somewebhook, data) {
    const findWebhooks = await this.prismaService.delivery.findMany({
      where: { someID: data.items?.[0]?.id.toString() },
    });
    
    const findPartner = await this.prismaService.partner.findFirst({
      where: {
        id: findWebhooks[0]?.partnerId,
      },
      select: {
        id: true,
        webhooks: {
          select: {
            webhookUrl: true,
          },
        },
      },
    });    

    const webhookUrl = findPartner!.webhooks[0]?.webhookUrl.toString();
    
    if (findWebhooks[0]?.partnerId === findPartner!.id)
      for (let i = 0; i < findPartner!.webhooks?.length; i++) {
        try {
          let webhookResponse = await fetch(webhookUrl, {
            method: 'post',
            body: JSON.stringify([someWebhook]),
          });
          if (!webhookResponse) {
// Right here is where I want to retry the fetch but I need to set a timeout to wait for a possible response first. 

          }
        } catch (err) {
          console.log(err);
        }
      }
  }
Tree
  • 1

0 Answers0