Search code examples
vert.xpgpool

JAXRS Service using Vert.x



I'm implementing a JAX-RS Service in an Application Server using Vert.x to store data in combination with Vert.x Pg pool. Storing data is quite straightforward as there's nothing to return to the client. However when it comes to a HTTP GET Request it becomes more complex. For example:

public List<Data> findAll() {
    List<Data> list = new ArrayList<>();
    pool.query("SELECT * FROM DATA", ar -> {
        if (ar.succeeded()) {

            RowSet rows = ar.result();

            for (Row row : rows) {
                list.add(new Data(row.getString(0), row.getString(1)));

            }
        } else {
            System.out.println("Failure: " + ar.cause().getMessage());
        }
    });

  return list;
}

So, as you can see, being "ar" a io.vertx.core.AsyncResult it returns immediately, with an empty ArrayList. I understand I should return an AsyncResult or a subclass of it, just I don't have an idea how could the client get the List of objects, when the query completed. Any idea / example? Thanks!


Solution

  • To create JAX-RS applications with the Reactive Pg Client, I would recommend to use Quarkus.

    You will get a PgPool provided by Quarkus that has a special API using the JDK CompletionStage. Then in Quarkus your JAX-RS methods may return a CompletionStage.

    Your method would look like:

    public CompletionStage<List<Data>> findAll() {
        pool.query("SELECT * FROM DATA")
            .thenApply(rows -> {
                List<Data> list = new ArrayList<>();
                for (Row row : rows) {
                    list.add(new Data(row.getString(0), row.getString(1)));
                }
                return list;
        });
    }
    

    Disclaimer: I work for Red Hat, I'm a Vert.x core team member and Quarkus contributor.