package dev.relism.models; import dev.relism.extension.FlashContext; import java.util.Optional; /** * Base class for class-based route handlers. * *
Annotate the subclass with {@link dev.relism.routing.Route @Route} and register it * via {@link dev.relism.extension.FlashApp#register} or {@link dev.relism.extension.FlashApp#scan}. * For one-off routes, prefer the lambda DSL ({@code app.get(path, handler)}). * *
{@code
* @Route(method = HttpMethod.GET, path = "/users")
* public class UserHandler extends RequestHandler {
* private UserService users;
*
* @Override protected void onInit() {
* users = require(UserService.class);
* }
*
* @Override public Object handle(Request req, Response res) {
* return users.findAll();
* }
* }
* }
*/
public abstract class RequestHandler {
private FlashContext ctx;
/**
* Called once by the framework after instantiation, before the first request.
* Injects the {@link FlashContext} and triggers {@link #onInit()}.
*
* Infrastructure method — do not call from user code. * Use {@link dev.relism.extension.FlashApp#register} or * {@link dev.relism.extension.FlashApp#scan} instead. */ public final void bind(FlashContext ctx) { this.ctx = ctx; onInit(); } /** * Override to cache services at boot time. Called once after {@link #bind}, * before any request reaches this handler. * *
Use {@link #require} and {@link #find} to retrieve services from the * {@link FlashContext}. Cache them in private fields so the hot-path * ({@link #handle}) has zero lookup overhead. * *
Important: if your class extends another handler base (e.g. * {@code JacksonHandler}), call {@code super.onInit()} first so the parent * can initialise its own services. * *
{@code
* @Override protected void onInit() {
* super.onInit();
* myService = require(MyService.class);
* }
* }
*/
protected void onInit() {}
/**
* Retrieves a required service from the {@link FlashContext}.
* Throws {@link IllegalStateException} if the service is not registered or
* this handler has not been bound yet.
*
* Typically called inside {@link #onInit()} to cache the result.
*
* @param type the service class
* @param