forked from ballerina-attic/ballerina-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
8_demo_async.bal
55 lines (49 loc) · 1.81 KB
/
8_demo_async.bal
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
// Move all the invocation and tweeting functionality to another function
// call it asynchronously
// To run it:
// ballerina run --config twitter.toml demo_async.bal
// To invoke:
// curl -X POST localhost:9090
// Invoke many times to show how quickly the function returns
// then go to the browser and refresh a few times to see how gradually new tweets appear
import ballerina/config;
import ballerina/http;
import wso2/twitter;
twitter:Client tw = new({
clientId: config:getAsString("clientId"),
clientSecret: config:getAsString("clientSecret"),
accessToken: config:getAsString("accessToken"),
accessTokenSecret: config:getAsString("accessTokenSecret"),
clientConfig: {}
});
http:Client homer = new("http://www.simpsonquotes.xyz");
@http:ServiceConfig {
basePath: "/"
}
service hello on new http:Listener(9090) {
@http:ResourceConfig {
path: "/",
methods: ["POST"]
}
resource function hi (http:Caller caller, http:Request request) returns error? {
// start is the keyword to make the call asynchronously.
_ = start doTweet();
http:Response res = new;
// just respond back with the text.
res.setPayload("Async call\n");
_ = check caller->respond(res);
return;
}
}
// Move the logic of getting the quote and pushing it to twitter
// into a separate function to be called asynchronously.
function doTweet() returns error? {
// We can remove all the error handling here because we call
// it asynchronously, don't want to get any output and
// don't care if it takes too long or fails.
var hResp = check homer->get("/quote");
var payload = check hResp.getTextPayload();
if (!payload.contains("#ballerina")){ payload = payload+" #ballerina"; }
_ = check tw->tweet(payload);
return;
}