Custom Functions - Context Methods
When you write custom 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 custom functions written in Java, Node.js, or Python. Custom functions written in Deluge do not support context methods.
Log
The context object provides logging support for your custom functions. You can log entries at various levels for debugging and monitoring purposes.
Java
| Method | Definition | Description |
|---|
| log | void log(String logData) | Logs an entry with the level INFO. |
| log | void log(String logData, Level level) | Logs an entry with the specified log level. |
import com.zoho.cloud.function.Context;
import com.zoho.cloud.function.basic.*;
import java.util.logging.Level;
public class javafn implements ZCFunction {
public void runner(Context context, BasicIO basicIO) throws Exception {
context.log("Log Data");
context.log("Log Data with level", Level.FINE);
}
}
Node.js
| Method | Definition | Description |
|---|
| log | log.ALL(logData) | Logs an entry with the level ALL. |
| log | log.CONFIG(logData) | Logs an entry with the level CONFIG. |
| log | log.FINE(logData) | Logs an entry with the level FINE. |
| log | log.FINER(logData) | Logs an entry with the level FINER. |
| log | log.FINEST(logData) | Logs an entry with the level FINEST. |
| log | log.INFO(logData) | Logs an entry with the level INFO. |
| log | log.SEVERE(logData) | Logs an entry with the level SEVERE. |
| log | log.WARNING(logData) | Logs an entry with the level WARNING. |
| log | log.getLogArray() | Gets the logs array (only in production). |
module.exports = async function(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());
}
Python
| Method | Definition | Description |
|---|
| log | log.ALL(logData) | Logs an entry with the level ALL. |
| log | log.CONFIG(logData) | Logs an entry with the level CONFIG. |
| log | log.FINE(logData) | Logs an entry with the level FINE. |
| log | log.FINER(logData) | Logs an entry with the level FINER. |
| log | log.FINEST(logData) | Logs an entry with the level FINEST. |
| log | log.INFO(logData) | Logs an entry with the level INFO. |
| log | log.SEVERE(logData) | Logs an entry with the level SEVERE. |
| log | log.WARNING(logData) | Logs an entry with the level WARNING. |
def runner(context, basicIO):
context.log.INFO("log INFO")
context.log.ALL("log ALL")
context.log.CONFIG("log CONFIG")
context.log.FINE("log FINE")
context.log.FINER("log FINER")
context.log.FINEST("log FINEST")
context.log.SEVERE("log SEVERE")
context.log.WARNING("log WARNING")
FunctionHome
FunctionHome returns the location of your custom function’s code. This is useful when you need to reference files relative to your function’s directory.
Java
| Method | Definition | Description |
|---|
| getFunctionHome | String getFunctionHome() | Gets the function home directory. |
import com.zoho.cloud.function.Context;
import com.zoho.cloud.function.basic.*;
public class javafunc implements ZCFunction {
public void runner(Context context, BasicIO basicIO) throws Exception {
String funcHome = context.getFunctionHome();
basicIO.write("FunctionHome: " + funcHome);
}
}
Node.js
| Method | Definition | Description |
|---|
| getFunctionHome | getFunctionHome() | Gets the function home directory. |
module.exports = async function(context, basicIO) {
var FuncHome = context.getFunctionHome();
basicIO.write("FunctionHome: " + FuncHome);
}
Python
| Method | Definition | Description |
|---|
| getFunctionHome | getFunctionHome() | Gets the function home directory. |
def runner(context, basicIO):
basicIO.write(context.getFunctionHome())
WritableDirectory
WritableDirectory is the path where you can perform file operations for that request. Use this when your custom function needs to create or modify files during execution.
Java
| Method | Definition | Description |
|---|
| getWritableDirectory | String getWritableDirectory() | Gets a writable directory for that request. |
import com.zoho.cloud.function.Context;
import com.zoho.cloud.function.basic.*;
public class javafunc implements ZCFunction {
public void runner(Context context, BasicIO basicIO) throws Exception {
String dir = context.getWritableDirectory();
basicIO.write("Writable DIR: " + dir);
}
}
Node.js
| Method | Definition | Description |
|---|
| getWritableDirectory | getWritableDirectory() | Gets a writable directory for that request. |
module.exports = async function(context, basicIO) {
var dir = context.getWritableDirectory();
basicIO.write("Writable DIR: " + dir);
}
Python
| Method | Definition | Description |
|---|
| getWritableDirectory | getWritableDirectory() | Gets a writable directory for that request. |
def runner(context, basicIO):
basicIO.write(context.getWritableDirectory())
Cache
Cache is an in-memory data store for quick retrieval of data. It is useful for storing transient data with a TTL (Time to Live).
Java
| Method | Definition | Description |
|---|
| getCache | com.zoho.cloud.cache.Cache getCache() | Returns a cache object. |
Cache methods:
| Method | Definition | Description |
|---|
| get | String get(String key) | Fetches data from cache. |
| set | boolean set(String key, String value) | Sets data in cache. |
| set | boolean set(String key, String value, Long expiry) | Sets data in cache with an expiry (in seconds). |
| del | boolean del(String key) | Deletes data in cache. |
import com.zoho.cloud.function.Context;
import com.zoho.cloud.function.basic.*;
import com.zoho.cloud.cache.Cache;
public class CacheJava implements ZCFunction {
public void runner(Context context, BasicIO basicIO) throws Exception {
String value = "xxSample_Token1xx";
String key = "Token1";
// Cache Object Creation
Cache cache = context.getCache();
// Cache set
if (!cache.set(key, value)) {
throw new Exception("cache set() error");
}
// Cache get
if (!value.equals(cache.get(key))) {
throw new Exception("Cache get error");
}
// Cache del
if (!cache.del(key)) {
throw new Exception("Del cache error");
}
// Cache set with expiry (in seconds)
if (!cache.set(key, value, 2L)) {
throw new Exception("cache set with expiry error");
}
basicIO.write("Cache worked");
}
}
Node.js
| Method | Definition | Description |
|---|
| getCache | getCache() | Returns a cache object. |
Cache methods:
| Method | Definition | Description |
|---|
| set | set(key, value[, expiry], callback) | Sets data in cache. |
| get | get(key, callback) | Gets data from cache. |
| del | del(key, callback) | Deletes data from cache. |
module.exports = async function(context, basicIO) {
var actionPromise = function() {
return new Promise(function(resolve, reject) {
// Cache object
let cache = 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");
});
});
});
});
});
}
var response = await actionPromise();
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
def runner(context, basicIO):
# Cache Object creation
cache = context.getCache()
key = 'pythontoken1'
value = 'mypythontoken1'
# Cache set
if cache.set(key, value) != True:
raise Exception('Error in cache set')
# Cache get
if value != cache.get(key):
raise Exception('Error in cache get')
# Cache delete
if cache.delete(key) != True:
raise Exception('Error in del cache')
# Cache set with expiry (in seconds)
if cache.set(key, value, 2) != True:
raise Exception('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 organisation.
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;
public class QueueJava implements ZCFunction {
public void runner(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 = async function(context, basicIO) {
var actionPromise = function() {
return new Promise(function(resolve, reject) {
// Queue object
var queue = context.getQueue();
// Produce a string
queue.produce("myqueue", "valuefromnodejs", function(err) {
if (err) reject("Failed produce");
// Produce a JSON object
var myObj = { 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");
});
});
});
});
});
}
var response = await actionPromise();
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. |
def runner(context, basicIO):
# Queue object
queue = context.getQueue()
# Push a JSON object
if queue.push("myqueue", {"k1": "v1"})["status"] != "Success":
raise Exception("Queue push error")
# Push a string
if queue.push("myqueue", "message1")["status"] != "Success":
raise Exception("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 custom 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. |
| start | String start() | Starts the docket. Returns the JobID. |
| stop | String stop() | Stops the docket. Returns the JobID. |
| getInvokeURL | JSONObject getInvokeURL() | Gets the invocation URL of the docket. |
| getInvokeURL | JSONObject getInvokeURL(Long timeOfValidity) | Gets the invocation URL with a validity period. |
import com.zoho.cloud.function.Context;
import com.zoho.cloud.function.basic.*;
import com.zoho.cloud.docket.*;
import org.json.*;
public class DocketTest implements ZCFunction {
public void runner(Context context, BasicIO basicIO) throws Exception {
// Docket object (router, hours, minutes, seconds, isRepeated, autoCreate)
Docket docket = context.getDocket("/testRouter", 0, 1, 0, false, true);
// Get Docket ID
basicIO.write(docket.getDocketID());
// Start docket with arguments
JSONObject json = new JSONObject();
json.put("testArg", "Awesome");
String jobID = docket.start(json);
// Get invocation URL
basicIO.write("InvokeURL for docket: " + docket.getInvokeURL());
}
}
Node.js
| Method | Definition | Description |
|---|
| getDocket | getDocket(docketInfo, callback) | Returns a docket object. |
You can pass docket info in the following ways:
- { docketname: “sampleDocket” } — by docket name.
- { docketid: “1796000000522017” } — by docket ID.
- { functionID: “…”, runner: “…”, hours: 0, minutes: 4, seconds: 0, isrepeated: false, autocreate: false } — with full configuration.
Docket methods:
| Method | Definition | Description |
|---|
| getDocketID | getDocketID() | Gets the current docket ID. |
| start | start([args,] callback) | Starts the docket. |
| stop | stop(callback) | Stops the docket. |
| getInvokeURL | getInvokeURL([TIME_OF_VALIDITY,] callback) | Gets the invocation URL for the docket. |
module.exports = async function(context, basicIO) {
var requestPromise = function() {
return new Promise(function(resolve, reject) {
context.getDocket({
docketname: "docketName"
}, function(docketErr, docket) {
if (docketErr) {
basicIO.write("error: " + JSON.stringify(docketErr));
reject("Failed");
} else {
basicIO.write(docket.getDocketID());
// Start docket
docket.start({}, function(errStart, jobID) {
if (errStart) {
reject("Failed");
} else {
basicIO.write("StartJobID: " + jobID);
// Stop docket
docket.stop(function(errStop, jobID) {
if (errStop) {
reject("Failed");
} else {
basicIO.write("StopJobID: " + jobID);
// Get invoke URL
docket.getInvokeURL(function(errURL, urlDetails) {
if (errURL) {
reject("Failed");
} else {
basicIO.write("URL: " + JSON.stringify(urlDetails));
resolve("Success");
}
});
}
});
}
});
}
});
});
}
var response = await requestPromise();
context.log.INFO(response);
}
Python
| Method | Definition | Description |
|---|
| getDocket | getDocket(docketInfo) | Gets the docket object. Pass a dictionary with docketname, docketid, or full configuration. |
Docket methods:
| Method | Definition | Description |
|---|
| getDocketID | getDocketID() | Gets the current docket ID. |
| start | start([args]) | Starts the docket. Returns the JobID. |
| stop | stop() | Stops the docket. Returns the JobID. |
| getInvokeURL | getInvokeURL([timeOfValidity]) | Gets the invocation URL for the docket. |
def runner(context, basicio):
docket = context.getDocket({
"docketname": "docketName"
})
basicio.write("Docketid: " + docket.getDocketID() + "\n")
basicio.write("JOBIDStart: " + docket.start() + "\n")
basicio.write("JOBIDStop: " + docket.stop() + "\n")
basicio.write("InvokeURL: " + docket.getInvokeURL() + "\n")
Stratus
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.
Java
| Method | Definition | Description |
|---|
| getStratusOperations | StratusOperations getStratusOperations() | Returns a Stratus object. |
Stratus methods:
| Method | Definition | Description |
|---|
| upload | JSONObject upload(InputStream inputStream, String keyName, Boolean isOverWriteAllowed) | Uploads a file to Stratus. |
| upload | JSONObject upload(InputStream inputStream, String keyName) | Uploads a file to Stratus (overwrite not allowed). |
| download | InputStream download(String keyName) | Downloads a file from Stratus. |
| delete | void delete(String keyName) | Deletes a file from Stratus. |
import com.zoho.cloud.function.Context;
import com.zoho.cloud.function.basic.*;
import java.io.*;
import org.apache.commons.io.IOUtils;
import com.zoho.cloud.stratus.StratusOperations;
public class StratusExample implements ZCFunction {
public void runner(Context context, BasicIO basicIO) throws Exception {
StratusOperations stratus = context.getStratusOperations();
// Upload
InputStream is = new ByteArrayInputStream("hello world".getBytes("UTF-8"));
basicIO.write(stratus.upload(is, "test.txt", false));
// Download
basicIO.write(IOUtils.toString(stratus.download("test.txt")));
// Delete
stratus.delete("test.txt");
}
}
Node.js
| Method | Definition | Description |
|---|
| getStratusOperations | getStratusOperations() | Returns a Stratus object. |
Stratus methods:
| Method | Definition | Description |
|---|
| upload | upload(keyName, isOverWriteAllowed, callback) | Uploads a file to Stratus. |
| download | download(keyName, callback) | Downloads a file from Stratus. |
| del | del(keyName, callback) | Deletes a file from Stratus. |
module.exports = async function(context, basicIO) {
var postData = "Hello from custom function";
// Stratus object
var stratusop = context.getStratusOperations();
// Upload
var req = stratusop.upload("f.txt", false, function(error, data) {
if (error) {
basicIO.write("Upload error");
return;
}
basicIO.write("Upload success");
});
req.on("error", function() {
basicIO.write("Error");
});
req.write(postData);
// Download
stratusop.download("f.txt", function(err, data) {
if (err) {
basicIO.write("Download error");
return;
}
basicIO.write("Download Data: " + data);
});
// Delete
stratusop.del("f.txt", function(error) {
if (error) {
basicIO.write("Delete error");
}
});
}
Python
| Method | Definition | Description |
|---|
| getStratusOperations | getStratusOperations() | Gets the Stratus object. |
Stratus methods:
| Method | Definition | Description |
|---|
| upload | upload(inputStream, keyName[, isOverWriteAllowed]) | Uploads a file to Stratus. |
| download | download(keyName) | Downloads a file from Stratus. |
| delete | delete(keyName) | Deletes a file from Stratus. |
def runner(context, basicIO):
stratus = context.getStratusOperations()
# Upload
data = "Python stratus upload"
stratus.upload(data, "pythonUploadFile", True)
# Download
data1 = stratus.download("pythonUploadFile")
if data != data1:
raise Exception("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 custom 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;
public class ConnectorExample implements ZCFunction {
@Override
public void runner(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);
}
}
}
Node.js
| Method | Definition | Description |
|---|
| getConnection | getConnection(connectionName) | Returns a connector object. |
Connector methods:
| Method | Definition | Description |
|---|
| makeRequest | makeRequest(options, callback) | Makes an asynchronous request. |
| makeRequestSync | makeRequestSync(params, postData) | Makes a synchronous request. |
module.exports = async function(context, basicIO) {
var connector = context.getConnection("connectionName");
var requestPromise = function() {
return new Promise(function(resolve, reject) {
var connReq = connector.makeRequest({
url: "https://api.example.com/data",
method: "POST",
headers: {
headerkey: "headervalue"
}
}, function(connRes) {
context.log.INFO(connRes.statusCode);
connRes.on("data", function(data) {
basicIO.write(data.toString());
});
connRes.on("end", function() {
resolve("Success");
});
connRes.on("error", function(error) {
basicIO.write(error.toString());
resolve("Failed");
});
});
connReq.on("error", function(error) {
basicIO.write(error.toString());
resolve("Failed");
});
connReq.write("Data to Post"); // Remove this line for GET requests
connReq.end();
});
}
var response = await requestPromise();
context.log.INFO(response);
}
Python
| Method | Definition | Description |
|---|
| getConnection | getConnection(connectionName) | Gets the connection object. |
Connector methods:
| Method | Definition | Description |
|---|
| makeRequest | makeRequest(url[, method][, headers][, data]) | Makes a request to an external URL using the connector. |
def runner(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.
Java
| Method | Definition | Description |
|---|
| getConnectorOperations | ConnectorOperations getConnectorOperations() | Returns a connector operations object. |
ConnectorOp methods:
| Method | Definition | Description |
|---|
| create | JSONObject create(String displayName, String serviceName, String scope) | Creates a new connection. |
| showAll | JSONArray showAll() | Shows all available connections. |
| showConnectionStatus | JSONObject showConnectionStatus(String linkName) | Shows the status of a connection. |
| revokeConnection | void revokeConnection(String linkName) | Revokes a connection. |
| checkExists | boolean checkExists(String linkName) | Checks if a connection exists. |
| deleteConnection | void deleteConnection(String linkName) | Deletes a connection. |
import com.zoho.cloud.function.Context;
import com.zoho.cloud.function.basic.*;
import com.zoho.cloud.connector.ConnectorOperations;
import org.json.*;
public class ConnectorOPJava implements ZCFunction {
public void runner(Context context, BasicIO basicIO) throws Exception {
ConnectorOperations conop = context.getConnectorOperations();
// Create
JSONArray scopeArray = new JSONArray();
scopeArray.put("https://www.googleapis.com/auth/gmail.send");
basicIO.write(conop.create("gmailConnector", "gmail", scopeArray.toString()));
// Show all
basicIO.write(conop.showAll());
// Show connection status
basicIO.write(conop.showConnectionStatus("gmailConnector"));
// Revoke
conop.revokeConnection("gmailConnector");
// Check exists
if (conop.checkExists("gmailConnector")) {
basicIO.write("connection exists");
}
// Delete
conop.deleteConnection("gmailConnector");
}
}
Node.js
| Method | Definition | Description |
|---|
| getConnectorOperations | getConnectorOperations() | Returns a connector operations object. |
ConnectorOp methods:
| Method | Definition | Description |
|---|
| create | create(args, callback) | Creates a connector. Args: { displayName, scope, serviceName }. |
| showAll | showAll(callback) | Shows all connectors. |
| showConnectionStatus | showConnectionStatus(linkName, callback) | Shows the status of a connector. |
| revokeConnection | revokeConnection(linkName, callback) | Revokes a connection. |
| deleteConnection | deleteConnection(linkName, callback) | Deletes a connector. |
| checkExists | checkExists(linkName, callback) | Checks if a connection exists. |
module.exports = async function(context, basicIO) {
var connectorop = context.getConnectorOperations();
var requestPromise = function() {
return new Promise(function(resolve, reject) {
// Create
var scope = '["https://www.googleapis.com/auth/gmail.readonly"]';
connectorop.create({
displayName: "gmail2",
scope: scope,
serviceName: "gmail"
}, function(createData, createErr) {
if (createErr != null) {
reject("Failed");
return;
}
basicIO.write(createData);
// Show all
connectorop.showAll(function(data, error) {
if (error) {
reject(error.toString());
return;
}
basicIO.write(data);
// Check exists
connectorop.checkExists("gmail2", function(checkdata, checkerror) {
if (checkerror) {
reject(checkerror.toString());
return;
}
basicIO.write("Exists: " + checkdata);
// Delete
connectorop.deleteConnection("gmail2", function(deleteError) {
if (!deleteError) {
reject("Delete failed");
return;
}
resolve("Success");
});
});
});
});
});
}
var response = await requestPromise();
context.log.INFO(response);
}
Python
| Method | Definition | Description |
|---|
| getConnectorOperations | getConnectorOperations() | Gets the connector operations object. |
ConnectorOp methods:
| Method | Definition | Description |
|---|
| create | create(displayName, serviceName[, scope]) | Creates a connector. |
| showAll | showAll() | Shows all connectors. |
| showConnectionStatus | showConnectionStatus(linkName) | Shows the status of a connection. |
| revokeConnection | revokeConnection(linkName) | Revokes a connection. |
| deleteConnection | deleteConnection(linkName) | Deletes a connection. |
| checkExists | checkExists(linkName) | Checks if a connection exists. |
import json
def runner(context, basicIO):
connop = context.getConnectorOperations()
connectionName = "pythonconnector1"
serviceName = "gmail"
# Create
lst = ["https://www.googleapis.com/auth/gmail.send"]
scope = json.dumps(lst)
connop.create(connectionName, serviceName, scope)
# Show all
basicIO.write(connop.showAll())
# Show connection status
context.log.INFO(connop.showConnectionStatus(connectionName))
# Check exists
if connop.checkExists(connectionName) != True:
raise Exception("connector not present")
# Delete
connop.deleteConnection(connectionName)
basicIO.write("ConnectorOP worked")