Cancel backendSrv.datasourceRequest

Hello,

I’m developing a react datasource plugin that makes calls to an external API via the Grafana proxy. The routing is set up in plugin.json and is working as expected when I use backendSrv.datasourceRequest() from DataSource.ts:

response = await this.backendSrv.datasourceRequest({
    url: url,
    method: method,
    data: body,
});

However, these requests are expensive and can take a long time. I would like the request to be cancelled if the user refreshes the page, or resubmits the query. Is there a way to signal this cancellation from the backendSrv? I see that it has a method called handleStreamCancellation and a field called HTTP_REQUEST_CANCELLED, but I’m not sure how to use these.

In case it’s useful, my API is ASP.NET Core and is using a CancellationToken to detect if the request was cancelled.

Thanks!

I believe I solved the issue. Found here: https://github.com/grafana/grafana/blob/81e9aa4de430ac9a865ecad91feb6cea91c0666c/public/app/core/services/backend_srv.ts

// A requestID is provided by the datasource as a unique identifier for a
// particular query. If the requestID exists, the promise it is keyed to
// is canceled, canceling the previous datasource request if it is still
// in-flight.

So I created a constant unique identifier for each type of request, and add it to the datasourceRequest:

let options = {
    url: url,
    method: method,
    data: body,
    requestId: requestId
};
response = await this.backendSrv.datasourceRequest(options);

And any request with the same requestId will cancel any previous request still running with the same ID.

2 Likes