Middlewares

Using Middlewares to modularize your application with ModularBr.

Middlewares are a widely used feature in various platforms and frameworks to manage application logic that runs before or after processing a request. They can be used to implement authentication, authorization, error handling, data compression, caching, and other functionalities.

By using middlewares in an application, it is possible to separate the business logic into distinct layers, making the application more modular and easier to maintain. Additionally, middlewares allow requests to be processed more efficiently as they can be applied at multiple points in the processing chain, allowing specific logic to be executed only when needed.

Another advantage of using middlewares is the ability to customize them to meet the specific needs of the application, enabling functionalities to be adjusted according to requirements.

In summary, middlewares are a powerful tool that can enhance the modularity, efficiency, and customization of an application, which is why they are widely used in different platforms and frameworks.

Adding Middlewares:

unit app.module;

interface

uses
  dmfbr.module,
  nfe.module;

type
  TNFeBeforeMiddleware = class(TRouteMiddleware)
  public
    class function Before(ARoute: TRouteAbstract): TRouteAbstract; override;
  end;

  TNFeAfterMiddleware = class(TRouteMiddleware)
  public
    class procedure After(ARoute: TRouteAbstract); override;
  end;
  
  TAppModule = class(TModule)
  private
    function BeforeMiddleware(ARoute: TRouteAbstract): TRouteAbstract;
    procedure AfterMiddleware(ARoute: TRouteAbstract);
  public
    function Routes: TRoutes; override;
  end;

implementation

{TNFeBeforeMiddleware}

class function TNFeBeforeMiddleware.BeforeMiddleware(
  ARoute: TRouteAbstract): TRouteAbstract;
begin
  //... Pegue ou altera aqui algo da rota, em seguida devolva ela.
  Result := ARoute;
end;

class procedure TNFeAfterMiddleware.After(ARoute: TRouteAbstract);
begin
  //...
end;

{ TAppModule }

function TAppModule.Routes: TRoutes;
begin
  // Rotas
  Result := [RouteModule('/nfe/:id',
                         TNFeModule,
                         [TNFeBeforeMiddleware, TNFeAfterMiddleware])];
end;

end.

Last updated