Как передать класс в качестве параметра функции для создания RESTful API в Delphi 10.2? - PullRequest
0 голосов
/ 23 октября 2019

Мы разрабатываем класс (RESTful) для ответа на запросы GET, POST, UPDATE, DELETE.

Методы этого класса должны иметь конечную точку (строку) и класс.

проблема в том, что в классы будут отправляться разные классы.

Например, мы отправили бы класс обслуживающего персонала, который вернет в методе GET список всех обслуживающего персонала или определенного обслуживающего персонала, если передан идентификатор обслуживающего персонала

Для этого же метода GET будет отправлен класс Delivery ... то есть разные классы, но они должны иметь одинаковое поведение (возвращать массив json со структурой класса).

Мой код может возвращать определенный класс, но мы не хотели бы повторять один и тот же код для нескольких классов.

Может кто-нибудь помочь?

function GET(Resource : String; Attendant:TAttendant):TJSONArray;
{CLASS DELIVERY}
unit Delivery;

interface

uses Generics.Collections, Rest.Json;

type

TDelivery = class
private
  FCashierId: Real;
  FPrice: Currency;
  FProduct: String;
  FProductId: Real;
  FValue: Currency;
  FVolume: Real;
public
  property CashierId: Real read FCashierId write FCashierId;
  property Price: Currency read FPrice write FPrice;
  property Product: String read FProduct write FProduct;
  property ProductId: Real read FProductId write FProductId;
  property Value: Currency read FValue write FValue;
  property Volume: Real read FVolume write FVolume;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TDelivery;
end;

implementation

{TDelivery}


function TDelivery.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TDelivery.FromJsonString(AJsonString: string): TDelivery;
begin
  result := TJson.JsonToObject<TDelivery>(AJsonString)
end;

end.


{CLASS ATTENDANT}
unit Attendant;

interface

uses Generics.Collections, Rest.Json;

type

TAttendant = class
private
  FCard: String;
  FId: Integer;
  FName: String;
public
  property card: String read FCard write FCard;
  property id: Integer read FId write FId;
  property name: String read FName write FName;

  constructor Create;
  destructor Destroy;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TAttendant;
end;

implementation

{TRootClass}
constructor TAttendant.Create;
begin
  inherited;
end;

destructor TAttendant.Destroy;
begin
  inherited;
end;

function TAttendant.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TAttendant.FromJsonString(AJsonString: string): TAttendant;
begin
  result := TJson.JsonToObject<TAttendant>(AJsonString)
end;


{RESTFUL API }
unit RESTful;

interface
uses
  REST.Client, System.DateUtils, REST.Types, System.JSON, REST.Json, Attendant, Delivery;

type
  TRESTful = class
    RESTClient:TRESTClient;
    RESTRequest:TRESTRequest;
    RESTResponse:TRESTResponse;
  private
    { Private declarations }
  public
    { Public declarations }
    function GET(Resource : String):TJSONArray;
  end;

const
  //endpoints
  SERVER  = 'localhost';
  PORT    = '212';
  ENDPOINT='http://' + SERVER + ':' + PORT + '/datasnap/rest/TSM/';

  //resources
  RESOURCE_ATTENDANTS = 'Attendants/';
  RESOURCE_DELIVERIES = 'Deliveries/';

implementation

uses
  System.SysUtils, Vcl.Dialogs;

{ TRESTful }

function TRESTful.GET(Resource: String): TJSONArray;
var
  RESTful:TRESTful;
  ObjetoJSON : TJSONObject;
  ArrayJSON : TArray<Attendant>;
begin
  RESTful:=TRESTful.Create;

  with RESTful do begin
    RESTClient:=TRESTClient.Create(nil);
    RESTRequest:=TRESTRequest.Create(nil);
    RESTResponse:=TRESTResponse.Create(nil);
    try
      try
        With RESTClient do Begin
          ResetToDefaults;
          Accept:='application/json, text/plain; q=0.9, text/html;q=0.8,';
          AcceptCharset:='UTF-8, *;q=0.8';
          AllowCookies:=true;
          AutoCreateParams:=true;
          HandleRedirects:=true;
          FallbackCharsetEncoding:='UTF-8';
          BaseURL:=Endpoint;
        End;
      except
        on E: Exception do Begin
            ShowMessage('RESTClient Error: '+ sLineBreak + E.Message);
        End;
      end;
    finally

    end;

    try
      try
        With RESTRequest do Begin
          ResetToDefaults;
          Accept:='application/json, text/plain; q=0.9, text/html;q=0.8,';
          AcceptCharset:='utf-8, *;q=0.8';
          ClearBody;
          AutoCreateParams:=True;
          Client:=RESTClient;
          HandleRedirects:=True;
          Method:=TRESTRequestMethod.rmGET;
          Resource:=Recurso;
          Response:=RESTResponse;
        End;
      except
        on E: Exception do Begin
            //ShowMessage('RESTRequest Error: '+ sLineBreak + E.Message);
        End;
      end;
    finally

    end;

    try
      try
        With RESTResponse do Begin
          ResetToDefaults;
          ContentType:='application/json';
        End;
      except
        on E: Exception do Begin
            //ShowMessage('RESTResponse error: '+ sLineBreak + E.Message);
        End;
      end;
    finally
      try
        RESTRequest.Execute;
        if RESTResponse.StatusCode = 200 then Begin
            //ShowMessage('success!' + sLineBreak + RESTResponse.Content.trim);
        end;
      except
        on E : Exception do
          //ShowMessage('Error: ' + sLineBreak + E.Message);
      end;
    end;
    FreeAndNil(RESTClient);
    FreeAndNil(RESTRequest);
    FreeAndNil(RESTResponse);
  end;
end;


как передать Attendant иДоставка классов по методу GET?

...