brookmiddlewarehandler.pas 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. (*
  2. Brook for Free Pascal
  3. Copyright (C) 2014-2019 Silvio Clecio
  4. See the file LICENSE.txt, included in this distribution,
  5. for details about the copyright.
  6. This library is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. *)
  10. { Middleware handler class. }
  11. unit BrookMiddlewareHandler;
  12. {$i brook.inc}
  13. interface
  14. uses
  15. BrookMiddleware, BrookRouter, BrookAction, BrookHttpDefs, BrookUtils;
  16. type
  17. { Handles exceptions for @link(TBrookMiddlewareHandler). }
  18. EBrookMiddlewareHandler = class(EBrookMiddleware);
  19. { Is a metaclass for @link(TBrookMiddlewareHandler) class. }
  20. TBrookMiddlewareHandlerClass = class of TBrookMiddlewareHandler;
  21. { Defines an enumerator to represent the middleware execution modes. }
  22. TBrookMiddlewareExecMode = (emBefore, emAfter);
  23. { Handles the middleware events. }
  24. TBrookMiddlewareHandler = class(TBrookMiddleware)
  25. private
  26. FExecMode: TBrookMiddlewareExecMode;
  27. FOnExecAction: TBrookExecuteActionEvent;
  28. protected
  29. procedure Loaded; override;
  30. procedure DoExecute(ASender: TObject; AAction: TBrookAction;
  31. ARequest: TBrookRequest; AResponse: TBrookResponse; const ANames,
  32. AValues: TBrookArrayOfString; ARoute: TBrookRoute;
  33. var AHandled: Boolean); override;
  34. published
  35. property OnExecute;
  36. { Defines if the middleware will be executed before or after the action
  37. execution. }
  38. property ExecMode: TBrookMiddlewareExecMode read FExecMode write FExecMode
  39. default emBefore;
  40. { Is triggered when the @code(DoExecute) method bound in this class is
  41. executed. }
  42. property OnExecAction: TBrookExecuteActionEvent read FOnExecAction
  43. write FOnExecAction;
  44. end;
  45. implementation
  46. { TBrookMiddlewareHandler }
  47. procedure TBrookMiddlewareHandler.Loaded;
  48. begin
  49. inherited Loaded;
  50. case FExecMode of
  51. emBefore: BindExecution(@TBrookRouter.Service.BeforeExecuteAction);
  52. emAfter: BindExecution(@TBrookRouter.Service.AfterExecuteAction);
  53. end;
  54. end;
  55. procedure TBrookMiddlewareHandler.DoExecute(ASender: TObject;
  56. AAction: TBrookAction; ARequest: TBrookRequest; AResponse: TBrookResponse;
  57. const ANames, AValues: TBrookArrayOfString; ARoute: TBrookRoute;
  58. var AHandled: Boolean);
  59. begin
  60. inherited DoExecute(ASender, AAction, ARequest, AResponse, ANames, AValues,
  61. ARoute, AHandled);
  62. if Assigned(FOnExecAction) then
  63. FOnExecAction(ASender, AAction, ARequest, AResponse, ANames, AValues,
  64. ARoute, AHandled);
  65. end;
  66. end.