When you write functions using Java, Node.js, or Python through the Zoho Finance CLI, you receive a context object. This context object provides various methods that let you interact with platform features such as logging, caching, queues, file storage, scheduled execution, and third-party connectors.
Note: You can use context methods only with functions written in Java, Node.js, or Python. Functions written in Deluge do not support context methods.
Log
The context object provides logging support for your functions. You can log entries at various levels for debugging and monitoring purposes.
module.exports=asyncfunction(context, basicIO) {
context.log.INFO("log data INFO");
context.log.ALL("log data ALL");
context.log.CONFIG("log data CONFIG");
context.log.FINE("log data FINE");
context.log.FINER("log data FINER");
context.log.FINEST("log data FINEST");
context.log.SEVERE("log data SEVERE");
context.log.WARNING("log data WARNING");
basicIO.write(context.log.getLogArray());
}
WritableDirectory is the path where you can perform file operations for that request. Use this when your function needs to create or modify files during execution.
module.exports=asyncfunction(context, basicIO) {
varactionPromise=function() {
returnnew Promise(function(resolve, reject) {
// Cache object
letcache=context.getCache();
// Cache set
cache.set("access_token", "xxSample1xx", function(value) {
if (value==false) reject("Cache set error");
// Cache set with expiry (in seconds)
cache.set("temp_key", "temp_value", 2, function(bool) {
if (bool==false) reject("Cache set error with expiry");
// Cache get
cache.get("access_token", function(body) {
if (body!="xxSample1xx") reject("Cache get error");
// Cache del
cache.del("access_token", function(body1) {
if (body1!=true) reject("Cache del error");
resolve("Success");
});
});
});
});
});
}
varresponse=awaitactionPromise();
basicIO.write(response);
}
Python
Method
Definition
Description
getCache
getCache()
Returns a cache object.
Cache methods:
Method
Definition
Description
set
set(key, value[, expiry]) -> bool
Sets data in cache.
get
get(key) -> str
Gets data from cache.
delete
delete(key) -> bool
Deletes data from cache.
import time
defrunner(context, basicIO):
# Cache Object creation cache = context.getCache()
key ='pythontoken1' value ='mypythontoken1'# Cache setif cache.set(key, value) !=True:
raiseException('Error in cache set')
# Cache getif value != cache.get(key):
raiseException('Error in cache get')
# Cache deleteif cache.delete(key) !=True:
raiseException('Error in del cache')
# Cache set with expiry (in seconds)if cache.set(key, value, 2) !=True:
raiseException('Error in set expiry')
basicIO.write('Cache worked')
Queue
The queue service is an in-memory queue with persistent storage (persisted for 12 hours by default). This queue service is common for all the functions in a specific organization.
Note:
topicName refers to the queue name.
offset determines the starting point for message retrieval.
range specifies the maximum number of messages to consume from the queue.
Java
Method
Definition
Description
getQueue
com.zoho.cloud.queue.Queue getQueue()
Returns a queue object.
Queue methods:
Method
Definition
Description
consume
JSONArray consume(String topicName, long offset)
Consumes data from the queue.
consume
JSONArray consume(String topicName, long offset, int range)
Consumes data from the queue with a specified range.
produce
void produce(String topicName, String value)
Produces data to the queue.
produce
void produce(String topicName, JSONObject value)
Produces JSON data to the queue.
import com.zoho.cloud.function.Context;
import com.zoho.cloud.function.basic.*;
import com.zoho.cloud.queue.*;
import org.json.JSONObject;
publicclassQueueJavaimplements ZCFunction {
publicvoidrunner(Context context, BasicIO basicIO) throws Exception {
Queue q = context.getQueue();
// Produce a string message q.produce("myqueue", "message1");
// Produce a JSON object JSONObject obj =new JSONObject();
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
q.produce("myqueue", obj);
// Consume without range basicIO.write(q.consume("myqueue", 0));
// Consume with range basicIO.write("Consume with range: "+ q.consume("myqueue", 0, 25));
}
}
Node.js
Method
Definition
Description
getQueue
getQueue()
Returns a queue object.
Queue methods:
Method
Definition
Description
consume
consume(options, callback)
Consumes data from the queue. Options: { topicName, offset, range }.
produce
produce(topicName, value, callback)
Produces data to the queue.
module.exports=asyncfunction(context, basicIO) {
varactionPromise=function() {
returnnew Promise(function(resolve, reject) {
// Queue object
varqueue=context.getQueue();
// Produce a string
queue.produce("myqueue", "valuefromnodejs", function(err) {
if (err) reject("Failed produce");
// Produce a JSON object
varmyObj= { name:"foo", num:123, is_vip:true };
queue.produce("myqueue", myObj, function(err1) {
if (err1) reject("Failed produce");
// Consume with range
queue.consume({ topicName:"myqueue", offset:0, range:50 },
function(err3, body) {
if (err3) reject("Failed consume");
basicIO.write(body);
// Consume without range (default range = 50)
queue.consume({ topicName:"myqueue", offset:0 },
function(err5, body1) {
if (err5) reject("Consume without range failed");
resolve("Success");
});
});
});
});
});
}
varresponse=awaitactionPromise();
basicIO.write(response);
}
Python
Method
Definition
Description
getQueue
getQueue()
Returns a queue object.
Queue methods:
Method
Definition
Description
pull
pull(topic, offset[, range]) -> json_str
Consumes data from the queue.
push
push(topic, value) -> json_str
Produces data to the queue.
defrunner(context, basicIO):
# Queue object queue = context.getQueue()
# Push a JSON objectif queue.push("myqueue", {"k1": "v1"})["status"] !="Success":
raiseException("Queue push error")
# Push a stringif queue.push("myqueue", "message1")["status"] !="Success":
raiseException("Queue push error")
# Pull with range basicIO.write(queue.pull("myqueue", 1, 10))
# Pull without range context.log.INFO(queue.pull("myqueue", 10))
basicIO.write("Queue worked")
Docket
Docket helps you schedule a function to run at a specific time or periodically. You can create a docket and store the jobID returned to track the status of execution.
Note:
A maximum of 5 jobs can be created per docket.
The minimum time to schedule a function is 60 seconds.
Java
Method
Definition
Description
getDocket
Docket getDocket(long docketID)
Returns a docket object using the docket ID.
getDocket
Docket getDocket(String docketName)
Returns a docket object using the docket name.
getDocket
Docket getDocket(String runner, int hours, int minutes, int seconds, boolean autoCreate)
Returns a docket object with the specified schedule.
getDocket
Docket getDocket(String runner, int hours, int minutes, int seconds, boolean isRepeatJob, boolean autoCreate)
Returns a docket object with repeat configuration.
Docket methods:
Method
Definition
Description
getDocketID
String getDocketID()
Returns the Docket ID.
start
String start(JSONObject values)
Starts the docket with arguments. Returns the JobID.
Stratus is an internal file storage service. A bucket is created for a portal, and all files are stored in that bucket. You can upload, download, and delete files using Stratus.
defrunner(context, basicIO):
stratus = context.getStratusOperations()
# Upload data ="Python stratus upload" stratus.upload(data, "pythonUploadFile", True)
# Download data1 = stratus.download("pythonUploadFile")
if data != data1:
raiseException("Download failed")
# Delete stratus.delete("pythonUploadFile")
basicIO.write("Stratus worked")
Connector
Connectors facilitate integration with third-party applications or services. They handle authentication, data transfer, and API interactions, allowing your function to access external resources.
Java
Method
Definition
Description
getConnection
Connector getConnection(String connectionName)
Returns a connector object.
Connector methods:
Method
Definition
Description
makeRequest
HttpURLConnection makeRequest(String externalURL)
Makes a request to an external URL using the connector.
makeRequest
HttpResponse makeRequest(HttpRequestBase request)
Makes a request using an HttpRequest object.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.logging.Level;
import com.zoho.cloud.connector.Connector;
import com.zoho.cloud.function.Context;
import com.zoho.cloud.function.basic.BasicIO;
import com.zoho.cloud.function.basic.ZCFunction;
publicclassConnectorExampleimplements ZCFunction {
@Overridepublicvoidrunner(Context context, BasicIO basicIO) throws Exception {
Connector connector = context.getConnection("connectionName");
// Make a request HttpURLConnection conn = connector.makeRequest("https://api.example.com/data");
conn.setRequestProperty("HeaderKey", "HeaderValue");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write("DataToBeSent".getBytes());
os.close();
int responseCode = conn.getResponseCode();
context.log("Response code is "+ responseCode, Level.FINE);
BufferedReader in =null;
if (responseCode < 300) {
in =new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
in =new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
String inputLine;
while ((inputLine = in.readLine()) !=null) {
basicIO.write(inputLine);
}
}
}
Makes a request to an external URL using the connector.
defrunner(context, basicIO):
url ="https://api.example.com/data"# Connector object con = context.getConnection("myconnector")
context.log.INFO("connector object created")
# Make request res = con.makeRequest(url, "GET")
context.log.INFO(res.read()) # Read the response content context.log.INFO(res.getcode()) # Get the status code context.log.INFO(res.info()) # Get the response headers basicIO.write("Connector worked")
Connector Operations
Connector operations allow you to create, view, revoke, and delete connectors programmatically from within your custom function.