Using TServerRequestQueue

by Erick Engelke
Aug 31, 2024

Often you will write EWB systems which must do a series of API calls to get a variety of data.

In some cases, you will need the results of one query to form the next query, in those cases you will need to use the successful completion handler of one request to schedule the next request.

But often I find I’m just needing to issue a bunch of queries to different services and I know all the request data in advance.

This is a perfect case for the TServerRequestQueue function. It lets you create a queue of requests and handle them in sequence. And if any request fails, it stops the queue processing.

You will need an OnComplete handler to handle the incoming data. Often you will write a specific handler for each data type.

You can write a general OnComplete (for all the successes and filter by URL), and an onError handler which generates a useful message if any request fails.

Here is successful output: :imagedir:images image

image

Here’s the code.

unit datetest;

interface

uses WebCore, WebUI, WebForms, WebCtrls, WebEdits, WebCals, WebCtnrs, WebLabels,
     WebHTTP, WebSession;

type

   TForm1 = class(TForm)
      ServerRequestQueue1: TServerRequestQueue;
      MultiLineEdit1: TMultiLineEdit;
      ServerRequest1: TServerRequest;
      procedure Form1Show(Sender: TObject);
   private
      { Private declarations }
      procedure srError( lsr : TServerrequest ; const msg : string );
      procedure srComplete( lsr : TServerRequest );
   public
      { Public declarations }
   end;

var
   Form1: TForm1;

implementation


procedure TForm1.srError( lsr : TServerrequest ; const msg : string );
begin
  multilineedit1.Lines.Add('Request: '+lsr.URL + ' Status Code: ' + IntToStr(lsr.StatusCode) );
end;

procedure TForm1.srComplete( lsr : TServerRequest );
begin
  multilineedit1.Lines.Add('Request: '+lsr.URL + ' Status Code ' +  IntToStr(lsr.statuscode) +' Data ' + lsr.ResponseContent.Text );
end;

procedure TForm1.Form1Show(Sender: TObject);
var
  sr : TServerRequest;
begin
  sr := ServerRequestQueue1.GetNewRequest;
  sr.URL := '1.php';
  sr.OnError := srError;
  sr.OnComplete := srComplete;
  ServerRequestQueue1.AddRequest( sr );

  sr := ServerRequestQueue1.GetNewRequest;
  sr.URL := '2.php';
  sr.OnError := srError;
  sr.OnComplete := srComplete;
  ServerRequestQueue1.AddRequest( sr );

  ServerRequestQueue1.ExecuteRequests;

end;

end.