import{_ as i,c as a,a0 as n,o as t}from"./chunks/framework.p2VkXzrt.js";const e="/assets/hdichain.FX-X2Mhu.png",o=JSON.parse('{"title":"⚡ Handler Default Implementations (HDI)","description":"","frontmatter":{"banner_title":"Flash - Handler Default Implementations","banner_description":"Leverage HDIs for cleaner and more maintainable route logic.","head":[["meta",{"name":"twitter:image","content":"/assets/banner-cards/flash-advanced-handler-default-implementations.png"}],["meta",{"name":"twitter:image:src","content":"https://docs.pixel-services.com/assets/banner-cards/flash-advanced-handler-default-implementations.png"}],["meta",{"name":"twitter:card","content":"summary_large_image"}],["meta",{"name":"twitter:image:height","content":"1280"}],["meta",{"name":"twitter:image:width","content":"669"}],["meta",{"name":"twitter:description","content":""}]]},"headers":[],"relativePath":"flash/advanced/handler-default-implementations.md","filePath":"flash/advanced/handler-default-implementations.md"}'),h={name:"flash/advanced/handler-default-implementations.md"};function l(p,s,k,r,d,E){return t(),a("div",null,s[0]||(s[0]=[n(`
Handler Default Implementations (HDIs) provide an elegant way to standardize common behaviors across multiple request handlers. By defining base handlers that extend RequestHandler (or chaining multiple base handlers together), you can modularize logic for common tasks like authentication, user data retrieval, and rate limiting.
HDIs are designed using the Chain of Responsibility pattern, making it easy to handle requests with layered logic.
Instead of repeating the same logic in each handler, create abstract handler classes that define common functionality. Your handler implementations then extend these base classes, inheriting the shared behavior while implementing the request-specific logic.
Creating an HDI is simple, but it's useful to follow some guidelines for clarity and maintainability:
RequestHandler.Request and Response objects.handle method to include common behavior. The handle method should return the response to the client and should call the Abstract Handler Method, which is implemented by the handler or next HDI in the chain.@Override
public Object handle() {
// Common logic here, then call the abstract method
return handleCustom();
}protected abstract Object handleCustom();INFO
Protected fields are accessible to the handler implementation inside the Abstract Handler Method. Example HDI :
public abstract class MyHDI extends RequestHandler {
protected String data;
public BaseHandler(Request req, Response res) {
super(req, res);
}
@Override
public Object handle() {
data = "Some data"; // Set the data
return handleCustom();
}
protected abstract Object handleCustom();
}Example Handler Implementation :
public class MyHandler extends MyHDI {
public MyHandler(Request req, Response res) {
super(req, res);
}
@Override
protected Object handleCustom() {
// The data is accessible here
System.out.println(data);
return "Response";
}
}Request and Response objects.@Override
protected Object handleCustom() {
// Custom logic here
return "Response";
}Now let's go over a simple example to demonstrate how HDIs work. Imagine you need to authenticate API requests by checking an API key. You can create an abstract APIKeyProtectedHandler that extends RequestHandler and handles the API key authentication:
public abstract class APIKeyProtectedHandler extends RequestHandler {
protected String apiKey;
public APIKeyProtectedHandler(Request req, Response res) {
super(req, res);
}
@Override
public Object handle() {
apiKey = req.header("X-API-Key");
if (apiKey == null || !isValidApiKey(apiKey)) {
res.status(403);
res.type("application/json");
return "{\\"error\\":\\"Invalid API Key\\"}";
}
return handleAuthorized();
}
protected abstract Object handleAuthorized();
private boolean isValidApiKey(String key) {
// Implement key validation logic, e.g., checking against a database
return true;
}
}Now, your API handler implementation only need to extend APIKeyProtectedHandler, ensuring every request has a valid API key before executing its logic:
@RouteInfo(endpoint = "/data", method = HttpMethod.GET)
public class GetDataHandler extends APIKeyProtectedHandler {
public GetDataHandler(Request req, Response res) {
super(req, res);
}
@Override
protected Object handleAuthorized() {
res.type("application/json");
return "{\\"data\\":\\"Your API response here\\"}";
}
}HDIs can be chained together to create multiple layers of logic. For example, if you need to authenticate a user and fetch their data from a database, you can create two HDIs:
ProtectedHandler ensures authentication.public abstract class ProtectedHandler extends RequestHandler {
protected String authToken;
public ProtectedHandler(Request req, Response res) {
super(req, res);
}
@Override
public Object handle() {
authToken = req.header("Authorization");
if (authToken == null || !isValidToken(authToken)) {
res.status(401);
res.type("application/json");
return "{\\"error\\":\\"Unauthorized\\"}";
}
return handleAuthenticated();
}
protected abstract Object handleAuthenticated();
}AuthenticatedHandler extends ProtectedHandler to fetch user data from the database, and overrides handleAuthenticated to ensure the user is authenticated before proceeding.public abstract class AuthenticatedHandler extends ProtectedHandler {
protected User user;
private String authToken; // inherited from ProtectedHandler
public AuthenticatedHandler(Request req, Response res) {
super(req, res);
}
@Override
protected Object handleAuthenticated() {
user = getUserFromDatabase(authToken);
if (user == null) {
res.status(403);
res.type("application/json");
return "{\\"error\\":\\"User not found\\"}";
}
return handleWithUser();
}
protected abstract Object handleWithUser();
}UserProfileHandler extends AuthenticatedHandler and implements handleWithUser to ensure the user is authenticated and their profile data has been fetched before proceeding.@RouteInfo(endpoint = "/profile", method = HttpMethod.GET)
public class UserProfileHandler extends AuthenticatedHandler {
public UserProfileHandler(Request req, Response res) {
super(req, res);
}
@Override
protected Object handleWithUser() {
res.type("application/json");
return "{\\"username\\":\\"" + user.getUsername() + "\\"}";
}
}