Skip to main content

Writing Functions (Node)

In this document we will create a function that can tell if our input is prime or not. Full code can be found on Github

Cape Function Format

Cape functions are defined as files within a directory.

Create a directory in your current directory called isprime. Inside it, create an example app.js file.

Here is the complete code to detect whether our input data was prime (or not):

const isPrime = (number) => {
if (number <= 1) {
return false;
}
for (let divisor = 2; divisor <= Math.sqrt(number); divisor++) {
if (number % divisor === 0) {
return false;
}
}
return true;
};

const capeHandler = (data) => {
const n = parseInt(data);
const result = isPrime(n);
let ret;
if (result) {
ret = `${n} is prime`;
} else {
ret = `${n} is NOT prime`;
}
return ret;
};

module.exports = {
capeHandler,
};
note

The entry point for all Cape functions written in Javascript is capeHandler. You'll notice we've added a helper function isPrime.

Our final project structure should look like:

$ ls isprime
app.js

Function input

Data is passed into the function as binary data in a Node Buffer. You can pass any kind of data you like via cape run or cape test.

In this example, we cast the binary input data to an int on this line:

const n = parseInt(data);

Function output

The output can be a buffer, string, JSON (object), or anything else (we would call toString() in the unknown case). Optionally, any of the previous can be wrapped in a promise or async function.

Alternative handlers may look like:

const capeHandler = async (data) => {
const _ = await ...
};

const capeHandler = (data) => {
return Promise.resolve(...);
};

Deployment

Node functions (as opposed to Cape functions written in Python) are deployed to a Node-specific pool of enclaves. You must use the --url option during deployment and execution to specify this pool.

cape deploy isprime --url wss://nodejs.capeprivacy.com

Dependencies

We can use npm to bundle Node dependencies. Let's start another example called reverse.

Create a new folder, initialize the npm package and install lodash.

mkdir reverse
cd reverse
npm init
npm install lodash --save

We can now require('lodash') in the app.js cape handler:

const _ = require('lodash');

const capeHandler = (data) => {
const text = data.toString('utf8');
return _.reverse(text.split('')).join('');
}

module.exports = {
capeHandler
};

Deploy the entire bundle:

cape deploy reverse --url wss://nodejs.capeprivacy.com

Run a sample invocation:

cape run <username>/reverse test --url wss://nodejs.capeprivacy.com
note

Cape's Node enclave pool is using the NodeJS 18.17.0 LTS runtime.

Full code examples for more sample functions can be found on Github.