Home > database >  In Vert.x, should REST endpoints return Future<T> or T?
In Vert.x, should REST endpoints return Future<T> or T?

Time:09-21

I am having a hard time finding documentation on which is the correct return type.

For example, if I have a REST endpoint which lookups and returns a String should the endpoint have a return type of Future<String> or String? Further, what impact would this have on the event loop (i.e. would returning String over Future<String> cause more blocking)?

Thanks!

CodePudding user response:

If you look at section (2) of the quick-start at https://vertx.io/get-started, you'll see chunk of code I've pasted below (I've added some numbered comments):

// Mount the handler for all incoming requests at every path and HTTP method
router
  .route()  // (1)
  .handler(context -> {  // (2)
    // Get the address of the request
    String address = context.request().connection().remoteAddress().toString();
    // Get the query parameter "name"
    MultiMap queryParams = context.queryParams();
    String name = queryParams.contains("name") ? queryParams.get("name") : "unknown";
    // Write a json response
    context.json(  // (3)
      new JsonObject()
        .put("name", name)
        .put("address", address)
        .put("message", "Hello "   name   " connected from "   address)
    );
  });

What this is doing is:

  1. Registering a Handler (basically a callback) that will be invoked for every request that the router receives.
  2. The handler will be called with a RoutingContext, which contains references to an HttpServerRequest object representing the current request, as well as an HttpServerResponse object representing the response. The latter allows you to control the response that is sent back to the client (ie headers, body, etc).
  3. context.json() is a convenience method for writing a JSON formatted response payload - the body will be correctly formatted, the content-type header will be set, etc.

Fundamentally, what .json() is doing is:

  final JsonObject myJson = ...;
  
  final Buffer myJsonBuffer = Json.encodeToBuffer(myJson);

  context.response()
      .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
      .write(myJsonBuffer);

Those last three lines are how the response is actually sent back to the client.

For a more detailed explanation, check out the Vert.x Web documentation regarding responses here.

CodePudding user response:

Out of the box Vert.x allows any primitive/simple type, String, or buffers to be sent as messages. However, it’s a convention and common practice in Vert.x to send messages as JSON

I guess this is the documentation you are looking for. You can return Strings to the eventBus. Though Json is mostly used

new JsonObject().put("key", "stringValue"); 

It's better to return the String than the Future. The Future will need special Codec.

  • Related