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
/
4_demo_transformations.bal
67 lines (59 loc) · 2.15 KB
/
4_demo_transformations.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
59
60
61
62
63
64
65
66
67
// Add twitter connector: import, create endpoint,
// create a new resource that invoke it
// To find it:
// ballerina search twitter
// To get it for tab completion:
// ballerina pull wso2/twitter
// To run it:
// ballerina run 4_demo_transformations.bal --b7a.config.file=twitter.toml
// To invoke:
// curl -X POST -d "Demo" localhost:9090
// this package helps read config files
import ballerina/config;
import ballerina/http;
// Pull and use wso2/twitter connector from http://central.ballerina.io
// It has the objects and APIs to make working with Twitter easy
import wso2/twitter;
import ballerina/stringutils;
// Twitter package defines this type of endpoint
// that incorporates the twitter API.
// We need to initialize it with OAuth data from apps.twitter.com.
// Instead of providing this confidential data in the code
// we read it from a toml file.
twitter:Client tw = new({
clientId: config:getAsString("clientId"),
clientSecret: config:getAsString("clientSecret"),
accessToken: config:getAsString("accessToken"),
accessTokenSecret: config:getAsString("accessTokenSecret"),
clientConfig: {}
});
@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? {
string payload = check request.getTextPayload();
// Transformation on the way to the twitter service - add hashtag.
if (!stringutils:contains(payload, "#ballerina")) {
payload = payload + " #ballerina";
}
twitter:Status st = check tw->tweet(payload);
// Transformation on the way out - generate a JSON and pass it back
// note that json is a first-class citizen
// and we can construct it from variables, data, and fields.
json myJson = {
text: payload,
id: st.id,
agent: "ballerina"
};
http:Response res = new;
// Pass back JSON instead of text.
res.setPayload(<@untainted> myJson);
_ = check caller->respond(res);
return;
}
}