Reputation: 7228
I have some repetitive code:
router.post("/fleets/:fleetid/vehicles/:boxid/ping").handler(ctx -> pingBox(pingBoxTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/wakeup").handler(ctx -> wakeUp(wakeupTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/passthrough").handler(ctx -> passthrough(passthroughTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/expert").handler(ctx -> passthrough(passthroughTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/door").handler(ctx -> door(doorTimer, oemUrl, ctx));
In the handler of these methods, I:
E.g.:
private void pingBox(Timer timer, String someArgs, RoutingContext ctx) {
log.debug("ping request");
Timer.Context timerCtx = timer.time();
ctx.put("timer", timerCtx);
ctx.response().headers().add("content-type", "text/plain");
ctx.response().end("pong");
timerCtx.stop();
}
How can I wrap the handler to avoid repeating code?
I've tried the following so far:
private void handleWithTimer(Timer timer, String url, RoutingContext ctx, BiConsumer<String, RoutingContext> handler){
log.debug("saving timer");
Timer.Context timerCtx = timer.time();
ctx.put("timer", timerCtx);
handler.accept(url, ctx);
timerCtx.stop();
}
but the result is not very readable:
.. .handler(ctx -> handleWithTimer(pingBoxTimer, oemUrl, ctx, (s, c) -> pingBox(oemUrl, ctx)));
There must be a more concise way. Any ideas?
Upvotes: 4
Views: 696
Reputation: 149
You can make your wrapping function more readable like this:
.handler(ctx -> handleWithTimer(pingBoxTimer, oemUrl, ctx, this::pingBox));
(of course only after adjusting your input parameters of pingBox, which it seems like you already did)
Upvotes: 4