unit Api.Server.Module;

interface

uses
  System.SysUtils, System.Classes, System.IniFiles,
  Sparkle.HttpServer.Module, Sparkle.HttpServer.Context,
  Sparkle.Comp.Server, Sparkle.Comp.HttpSysDispatcher,
  XData.Comp.Server, XData.Comp.ConnectionPool, XData.OpenApi.Service,
  Sparkle.Comp.GenericMiddleware, Sparkle.Comp.JwtMiddleware,
  Sparkle.Comp.BasicAuthMiddleware, Sparkle.Comp.CorsMiddleware, Common.Middleware.Logging,
  Sparkle.Comp.CompressMiddleware, VCL.Forms, XData.Server.Module, Common.Logging;

type
  TApiServerModule = class(TDataModule)
    SparkleHttpSysDispatcher: TSparkleHttpSysDispatcher;
    XDataServer: TXDataServer;
    XDataServerCompress: TSparkleCompressMiddleware;
    XDataServerCORS: TSparkleCorsMiddleware;
    XDataServerGeneric: TSparkleGenericMiddleware;
    procedure XDataServerGenericMiddlewareCreate(Sender: TObject; var Middleware:
        IHttpServerMiddleware);
  public
    procedure StartApiServer(ABaseUrl: string);
  end;

const
  SERVER_PATH_SEGMENT = 'api';

var
  ApiServerModule: TApiServerModule;

implementation


{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}


procedure TApiServerModule.StartApiServer(ABaseUrl: string);
var
  Url: string;
begin
  RegisterOpenApiService;

  Url := ABaseUrl;
  if not Url.EndsWith('/') then
    Url := Url + '/';
  Url := Url + SERVER_PATH_SEGMENT;

  XDataServer.BaseUrl := Url;

  SparkleHttpSysDispatcher.Start;
  Logger.Log(1, Format('Api server module listening at "%s"', [XDataServer.BaseUrl]));
end;

procedure TApiServerModule.XDataServerGenericMiddlewareCreate(Sender: TObject;
    var Middleware: IHttpServerMiddleware);
begin
  Middleware := TLoggingMiddleware.Create(Logger);
end;


end.
