In a ballerina HTTP method, is it possible to call an external API and return a response to the client and then handle the response from the external API? Here, the usecase is such that after the method returns it's response, if the external API successfully return a response, that response value needs to be added to a cache. Then when the HTTP method is called again, that response needs to be extracted from the Cache.
cache:Cache cache = new ({
capacity: 1000,
evictionFactor: 0.2,
cleanupInterval: 3600
});
resource function post getEntitlementsWithoutOrgId(http:Caller caller, http:Request request) returns error? {
string jsonString = check request.getTextPayload();
json jsonObj = check value:fromJsonString(jsonString);
string role = <string>check jsonObj.role;
json returnPayload = <json>check cache.get(role);
http:Response response = new;
if (returnPayload != null) {
response.statusCode = http:STATUS_OK;
} else {
http:Client httpEndpoint = check new ("https://test.com", {
timeout: 0.9
});
http:Response getResponse = check httpEndpoint->get("/roles/" + role + "/entitlements", {"X_API_KEY": "X_API_KEY"});
returnPayload = check getResponse.getJsonPayload();
if (returnPayload != null) {
check cache.put(role, returnPayload);
response.statusCode = http:STATUS_OK;
} else {
response.statusCode = getResponse.statusCode;
}
}
response.setJsonPayload(returnPayload);
check caller->respond(response);
}
When you do
check cache.get(role)
, if the relevant entry is not present in the cache you are returning immediately. Following is a sample related to the above requirement.