Created
October 11, 2016 07:48
-
-
Save aesteve/4cf52a42f0439ab1f9ebebaf17121c5c to your computer and use it in GitHub Desktop.
Creating interceptor-like logic just with handlers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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