forked from vert-x3/vertx-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.ceylon
147 lines (128 loc) · 5.01 KB
/
Server.ceylon
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import io.vertx.ceylon.web { ... }
import io.vertx.ceylon.core { Verticle }
import io.vertx.ceylon.jdbc { ... }
import io.vertx.ceylon.sql { SQLConnection,
ResultSet,
UpdateResult }
import ceylon.json { JsonObject=Object, JsonArray=Array }
import io.vertx.ceylon.web.handler {
bodyHandler
}
import io.vertx.ceylon.core.http {
HttpServerResponse
}
shared class Server() extends Verticle() {
shared actual void start() {
value client = jdbcClient.createShared(vertx, JsonObject {
"url"->"jdbc:hsqldb:mem:test?shutdown=true",
"driver_class"->"org.hsqldb.jdbcDriver"
});
setUpInitialData(client, () {
value router_ = router.router(vertx);
router_.route().handler(bodyHandler.create().handle);
// in order to minimize the nesting of call backs we can put the JDBC connection on the context for all routes
// that match /products
// this should really be encapsulated in a reusable JDBC handler that uses can just add to their app
router_.route("/products/*").handler {
void requestHandler(RoutingContext routingContext) {
client.getConnection((SQLConnection|Throwable conn) {
if (is Throwable conn) {
routingContext.fail(conn);
return;
}
// save the connection on the context
routingContext.put("conn", conn);
// we need to return the connection back to the jdbc pool. In order to do that we need to close it, to keep
// the remaining code readable one can add a headers end handler to close the connection.
routingContext.addHeadersEndHandler(() => conn.close());
routingContext.next();
});
}
}.failureHandler {
void failureHandler(RoutingContext routingContext) {
if (exists conn = routingContext.get<SQLConnection>("conn")) {
conn.close();
}
}
};
router_.get("/products/:productID").handler(handleGetProduct);
router_.post("/products").handler(handleAddProduct);
router_.get("/products").handler(handleListProducts);
vertx.createHttpServer().requestHandler(router_.accept).listen(8080);
});
}
void handleGetProduct(RoutingContext routingContext) {
value response = routingContext.response();
if (exists productID = routingContext.request().getParam("productID")) {
assert(exists conn = routingContext.get<SQLConnection>("conn"));
conn.queryWithParams("SELECT id, name, price, weight FROM products where id = ?", JsonArray {
parseInteger(productID)
}, (ResultSet|Throwable result) {
if (is Throwable result) {
sendError(500, response);
return;
}
if (exists row = result.rows?.first) {
response.putHeader("content-type", "application/json").end(row.string);
} else {
sendError(404, response);
}
});
} else {
sendError(400, response);
}
}
void handleAddProduct(RoutingContext routingContext) {
value response = routingContext.response();
assert(exists conn = routingContext.get<SQLConnection>("conn"));
value product = routingContext.getBodyAsJson();
if (exists product) {
conn.updateWithParams("INSERT INTO products (name, price, weight) VALUES (?, ?, ?)", JsonArray {
product.getString("name"), product.getFloat("price"), product.getInteger("weight")
}, (UpdateResult|Throwable result) {
if (is Throwable result) {
sendError(500, response);
return;
}
response.end();
});
} else {
sendError(500, response);
}
}
void handleListProducts(RoutingContext routingContext) {
value response = routingContext.response();
assert(exists conn = routingContext.get<SQLConnection>("conn"));
conn.query("SELECT id, name, price, weight FROM products", (ResultSet|Throwable result) {
if (is Throwable result) {
sendError(500, response);
return;
}
value arr = JsonArray();
result.rows?.each(arr.add);
response.putHeader("content-type", "application/json").end(arr.string);
});
}
void sendError(Integer statusCode, HttpServerResponse response) {
response.setStatusCode(statusCode).end();
}
void setUpInitialData(JDBCClient client, void done()) {
print("calling get connection");
client.getConnection((SQLConnection|Throwable conn) {
if (is Throwable conn) {
throw conn;
}
conn.execute("CREATE TABLE IF NOT EXISTS products(id INT IDENTITY, name VARCHAR(255), price FLOAT, weight INT)", (Throwable? err) {
if (exists err) {
throw err;
}
conn.execute("INSERT INTO products (name, price, weight) VALUES ('Egg Whisk', 3.99, 150), ('Tea Cosy', 5.99, 100), ('Spatula', 1.00, 80)", (Throwable? err) {
if (exists err) {
throw err;
}
done();
});
});
});
}
}