Zoho books logo Help Docs
/

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

MethodDefinitionDescription
logvoid log(String logData)Logs an entry with the level INFO.
logvoid 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

MethodDefinitionDescription
loglog.ALL(logData)Logs an entry with the level ALL.
loglog.CONFIG(logData)Logs an entry with the level CONFIG.
loglog.FINE(logData)Logs an entry with the level FINE.
loglog.FINER(logData)Logs an entry with the level FINER.
loglog.FINEST(logData)Logs an entry with the level FINEST.
loglog.INFO(logData)Logs an entry with the level INFO.
loglog.SEVERE(logData)Logs an entry with the level SEVERE.
loglog.WARNING(logData)Logs an entry with the level WARNING.
loglog.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

MethodDefinitionDescription
loglog.ALL(logData)Logs an entry with the level ALL.
loglog.CONFIG(logData)Logs an entry with the level CONFIG.
loglog.FINE(logData)Logs an entry with the level FINE.
loglog.FINER(logData)Logs an entry with the level FINER.
loglog.FINEST(logData)Logs an entry with the level FINEST.
loglog.INFO(logData)Logs an entry with the level INFO.
loglog.SEVERE(logData)Logs an entry with the level SEVERE.
loglog.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

MethodDefinitionDescription
getFunctionHomeString 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

MethodDefinitionDescription
getFunctionHomegetFunctionHome()Gets the function home directory.
module.exports = async function(context, basicIO) {
    var FuncHome = context.getFunctionHome();
    basicIO.write("FunctionHome: " + FuncHome);
}

Python

MethodDefinitionDescription
getFunctionHomegetFunctionHome()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

MethodDefinitionDescription
getWritableDirectoryString 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

MethodDefinitionDescription
getWritableDirectorygetWritableDirectory()Gets a writable directory for that request.
module.exports = async function(context, basicIO) {
    var dir = context.getWritableDirectory();
    basicIO.write("Writable DIR: " + dir);
}

Python

MethodDefinitionDescription
getWritableDirectorygetWritableDirectory()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

MethodDefinitionDescription
getCachecom.zoho.cloud.cache.Cache getCache()Returns a cache object.

Cache methods:

MethodDefinitionDescription
getString get(String key)Fetches data from cache.
setboolean set(String key, String value)Sets data in cache.
setboolean set(String key, String value, Long expiry)Sets data in cache with an expiry (in seconds).
delboolean 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

MethodDefinitionDescription
getCachegetCache()Returns a cache object.

Cache methods:

MethodDefinitionDescription
setset(key, value[, expiry], callback)Sets data in cache.
getget(key, callback)Gets data from cache.
deldel(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

MethodDefinitionDescription
getCachegetCache()Returns a cache object.

Cache methods:

MethodDefinitionDescription
setset(key, value[, expiry]) -> boolSets data in cache.
getget(key) -> strGets data from cache.
deletedelete(key) -> boolDeletes 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 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

MethodDefinitionDescription
getQueuecom.zoho.cloud.queue.Queue getQueue()Returns a queue object.

Queue methods:

MethodDefinitionDescription
consumeJSONArray consume(String topicName, long offset)Consumes data from the queue.
consumeJSONArray consume(String topicName, long offset, int range)Consumes data from the queue with a specified range.
producevoid produce(String topicName, String value)Produces data to the queue.
producevoid 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

MethodDefinitionDescription
getQueuegetQueue()Returns a queue object.

Queue methods:

MethodDefinitionDescription
consumeconsume(options, callback)Consumes data from the queue. Options: { topicName, offset, range }.
produceproduce(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

MethodDefinitionDescription
getQueuegetQueue()Returns a queue object.

Queue methods:

MethodDefinitionDescription
pullpull(topic, offset[, range]) -> json_strConsumes data from the queue.
pushpush(topic, value) -> json_strProduces 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

MethodDefinitionDescription
getDocketDocket getDocket(long docketID)Returns a docket object using the docket ID.
getDocketDocket getDocket(String docketName)Returns a docket object using the docket name.
getDocketDocket getDocket(String runner, int hours, int minutes, int seconds, boolean autoCreate)Returns a docket object with the specified schedule.
getDocketDocket getDocket(String runner, int hours, int minutes, int seconds, boolean isRepeatJob, boolean autoCreate)Returns a docket object with repeat configuration.

Docket methods:

MethodDefinitionDescription
getDocketIDString getDocketID()Returns the Docket ID.
startString start(JSONObject values)Starts the docket with arguments. Returns the JobID.
startString start()Starts the docket. Returns the JobID.
stopString stop()Stops the docket. Returns the JobID.
getInvokeURLJSONObject getInvokeURL()Gets the invocation URL of the docket.
getInvokeURLJSONObject 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

MethodDefinitionDescription
getDocketgetDocket(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:

MethodDefinitionDescription
getDocketIDgetDocketID()Gets the current docket ID.
startstart([args,] callback)Starts the docket.
stopstop(callback)Stops the docket.
getInvokeURLgetInvokeURL([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

MethodDefinitionDescription
getDocketgetDocket(docketInfo)Gets the docket object. Pass a dictionary with docketname, docketid, or full configuration.

Docket methods:

MethodDefinitionDescription
getDocketIDgetDocketID()Gets the current docket ID.
startstart([args])Starts the docket. Returns the JobID.
stopstop()Stops the docket. Returns the JobID.
getInvokeURLgetInvokeURL([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

MethodDefinitionDescription
getStratusOperationsStratusOperations getStratusOperations()Returns a Stratus object.

Stratus methods:

MethodDefinitionDescription
uploadJSONObject upload(InputStream inputStream, String keyName, Boolean isOverWriteAllowed)Uploads a file to Stratus.
uploadJSONObject upload(InputStream inputStream, String keyName)Uploads a file to Stratus (overwrite not allowed).
downloadInputStream download(String keyName)Downloads a file from Stratus.
deletevoid 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

MethodDefinitionDescription
getStratusOperationsgetStratusOperations()Returns a Stratus object.

Stratus methods:

MethodDefinitionDescription
uploadupload(keyName, isOverWriteAllowed, callback)Uploads a file to Stratus.
downloaddownload(keyName, callback)Downloads a file from Stratus.
deldel(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

MethodDefinitionDescription
getStratusOperationsgetStratusOperations()Gets the Stratus object.

Stratus methods:

MethodDefinitionDescription
uploadupload(inputStream, keyName[, isOverWriteAllowed])Uploads a file to Stratus.
downloaddownload(keyName)Downloads a file from Stratus.
deletedelete(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

MethodDefinitionDescription
getConnectionConnector getConnection(String connectionName)Returns a connector object.

Connector methods:

MethodDefinitionDescription
makeRequestHttpURLConnection makeRequest(String externalURL)Makes a request to an external URL using the connector.
makeRequestHttpResponse 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

MethodDefinitionDescription
getConnectiongetConnection(connectionName)Returns a connector object.

Connector methods:

MethodDefinitionDescription
makeRequestmakeRequest(options, callback)Makes an asynchronous request.
makeRequestSyncmakeRequestSync(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

MethodDefinitionDescription
getConnectiongetConnection(connectionName)Gets the connection object.

Connector methods:

MethodDefinitionDescription
makeRequestmakeRequest(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

MethodDefinitionDescription
getConnectorOperationsConnectorOperations getConnectorOperations()Returns a connector operations object.

ConnectorOp methods:

MethodDefinitionDescription
createJSONObject create(String displayName, String serviceName, String scope)Creates a new connection.
showAllJSONArray showAll()Shows all available connections.
showConnectionStatusJSONObject showConnectionStatus(String linkName)Shows the status of a connection.
revokeConnectionvoid revokeConnection(String linkName)Revokes a connection.
checkExistsboolean checkExists(String linkName)Checks if a connection exists.
deleteConnectionvoid 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

MethodDefinitionDescription
getConnectorOperationsgetConnectorOperations()Returns a connector operations object.

ConnectorOp methods:

MethodDefinitionDescription
createcreate(args, callback)Creates a connector. Args: { displayName, scope, serviceName }.
showAllshowAll(callback)Shows all connectors.
showConnectionStatusshowConnectionStatus(linkName, callback)Shows the status of a connector.
revokeConnectionrevokeConnection(linkName, callback)Revokes a connection.
deleteConnectiondeleteConnection(linkName, callback)Deletes a connector.
checkExistscheckExists(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

MethodDefinitionDescription
getConnectorOperationsgetConnectorOperations()Gets the connector operations object.

ConnectorOp methods:

MethodDefinitionDescription
createcreate(displayName, serviceName[, scope])Creates a connector.
showAllshowAll()Shows all connectors.
showConnectionStatusshowConnectionStatus(linkName)Shows the status of a connection.
revokeConnectionrevokeConnection(linkName)Revokes a connection.
deleteConnectiondeleteConnection(linkName)Deletes a connection.
checkExistscheckExists(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")

Was this document helpful?
Yes
No

Thank you for your feedback!