This repository has been archived by the owner on Oct 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
8_demo_async.bal
58 lines (52 loc) · 1.85 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
56
57
58
// Move all the invocation and tweeting functionality to another function
// call it asynchronously
// To run it:
// ballerina run 8_demo_async.bal --b7a.config.file=twitter.toml
// 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 ballerina/stringutils;
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://quotes.rest");
@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("/qod.json");
var payload = check hResp.getTextPayload();
if (!stringutils:contains(payload, "#ballerina")) {
payload = payload + " #ballerina";
}
_ = check tw->tweet(payload);
return;
}