Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: set timeout to newrelic's request #19

Merged
merged 1 commit into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading