forked from vert-x3/vertx-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Client.java
54 lines (46 loc) · 1.43 KB
/
Client.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package io.vertx.example.jpms.sqlclient;
import io.vertx.core.*;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonArray;
import io.vertx.pgclient.PgBuilder;
import io.vertx.pgclient.PgConnectOptions;
import io.vertx.sqlclient.Pool;
import java.util.stream.Collectors;
/*
* @author <a href="mailto:[email protected]">Paulo Lopes</a>
*/
public class Client extends VerticleBase {
private PgConnectOptions database;
private HttpServer server;
private Pool client;
// Tested with test containers
public Client(PgConnectOptions database) {
this.database = database;
}
public Future<?> start() {
client = PgBuilder.pool()
.connectingTo(database)
.using(vertx)
.build();
server = vertx.createHttpServer()
.requestHandler(req -> {
client.withConnection(conn -> conn
.query("SELECT * FROM periodic_table")
.collecting(Collectors.mapping(row -> row.toJson(), Collectors.toList()))
.execute()).onComplete(ar -> {
if (ar.succeeded()) {
req
.response()
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.end(new JsonArray(ar.result().value()).encode());
} else {
req.response()
.setStatusCode(500)
.end(ar.cause().toString());
}
});
});
return server.listen(8080);
}
}