Skip to content

Commit

Permalink
feat: set timeout to newrelic's request
Browse files Browse the repository at this point in the history
  • Loading branch information
smoya committed Jan 12, 2024
1 parent 122f2c3 commit 2446a75
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
17 changes: 14 additions & 3 deletions src/sinks/newrelic.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* global RequestInit */
import { Sink } from '../sink';
import { Metrics, MetricType } from '../metrics';

Expand Down Expand Up @@ -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<void> {
async send(metrics: Metrics, timeout = 2000): Promise<void> {
const nrMetrics = [];
for (const metric of metrics) {
switch (metric.type) {
Expand All @@ -44,18 +45,28 @@ 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) {
throw new Error(`Failed to send metrics to New Relic Metrics API: ${response.status} ${response.statusText}`);
}
}
}

async function fetchWithTimeout(resource: string, options: RequestInit, timeout: number): Promise<Response> {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
options.signal = controller.signal;
const response = await fetch(resource, options);
clearTimeout(id);

return response;
}
3 changes: 2 additions & 1 deletion test/sinks/newrelic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 2446a75

Please sign in to comment.