Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating interceptor-like logic just with handlers
public class InterceptorExample extends AbstractVerticle {
public final static String API_PATH = "/api/v1/";
public final static String STATIC_FILES = "/static/";
// ...
private Router router;
@Override
public void start(Future<Void> future) {
router = Router.router(vertx);
attachRoutes();
vertx
.createHttpServer()
.requestHandler(router::accept)
.listen(future.map<Void>(s -> null).completer());
}
private void attachRoutes() {
router.get(STATIC_FILES + "*").handler(SomeUtilityClass::createCacheHeaders);
router.get(STATIC_FILES + "*").handler(StaticHandler.create());
jsonRoute(API_PATH + "orders", ctx -> {
final Collection<Order> orders = yourBusinessService.getOrders();
ctx.put("data", orders);
ctx.next();
});
}
private void jsonRoute(String path, Handler<RoutingContext> businessLogic) {
router.route(path).handler(JsonUtils::prepareHeaders);
router.route(path).handler(businessLogic);
router.route(path).handler(JsonUtils::marshallResult);
}
}
interface JsonUtils { // this is what you're calling an interceptor
static void prepareHeaders(RoutingContext ctx) {
if (!ctx.request.headers().contains("something")) {
ctx.fail(400);
return;
}
ctx.response().putHeader(CONTENT_TYPE, "application/json");
ctx.next();
}
static void marshallResult(RoutingContext ctx) {
ctx.response().end(ctx.get("data").toJsonObject()); // or Jackson if you want to stay generic, or whatever you need
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.