From 2446a75de37f2998099a5aceec8c2c17b50fd074 Mon Sep 17 00:00:00 2001 From: Sergio Moya <1083296+smoya@users.noreply.github.com> Date: Fri, 12 Jan 2024 13:45:18 +0100 Subject: [PATCH] feat: set timeout to newrelic's request --- src/sinks/newrelic.ts | 17 ++++++++++++++--- test/sinks/newrelic.spec.ts | 3 ++- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/sinks/newrelic.ts b/src/sinks/newrelic.ts index f371ca7..93b41b4 100644 --- a/src/sinks/newrelic.ts +++ b/src/sinks/newrelic.ts @@ -1,3 +1,4 @@ +/* global RequestInit */ import { Sink } from '../sink'; import { Metrics, MetricType } from '../metrics'; @@ -28,7 +29,7 @@ export class NewRelicSink implements Sink { protected readonly apiEndpoint = 'https://metric-api.eu.newrelic.com/metric/v1' ) {} - async send(metrics: Metrics): Promise { + async send(metrics: Metrics, timeout = 2000): Promise { const nrMetrics = []; for (const metric of metrics) { switch (metric.type) { @@ -44,14 +45,14 @@ export class NewRelicSink implements Sink { } // Send the metric to the New Relic Metrics API - const response = await fetch(this.apiEndpoint, { + const response = await fetchWithTimeout(this.apiEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-License-Key': this.licenseKey }, body: JSON.stringify([{ metrics: nrMetrics }]) - }); + }, timeout); // Check the response status and throw an error if it's not successful if (!response.ok) { @@ -59,3 +60,13 @@ export class NewRelicSink implements Sink { } } } + +async function fetchWithTimeout(resource: string, options: RequestInit, timeout: number): Promise { + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), timeout); + options.signal = controller.signal; + const response = await fetch(resource, options); + clearTimeout(id); + + return response; +} diff --git a/test/sinks/newrelic.spec.ts b/test/sinks/newrelic.spec.ts index 196bd96..e12ceb9 100644 --- a/test/sinks/newrelic.spec.ts +++ b/test/sinks/newrelic.spec.ts @@ -27,7 +27,8 @@ describe('Recorder', function() { 'Content-Type': 'application/json', 'X-License-Key': 'FAKE_LICENSE_KEY' }, - method: 'POST' + method: 'POST', + signal: new AbortController().signal }; await sink.send(metrics);