Saltar al contendio prinicipal

Custom Javascript Code-2.0.0

FAAS JS runner.
key: CCJS

Overview

With the Custom JavaScript Code stage-bot, you can add extra customization to your routines. This powerful tool runs safely in a sandboxed node.js environment with the ability to extract, process, and return data for use in the rest of your routine.

Simply add your JavaScript code into the source code field in the stage-bot's settings panel:

ccjs settings panel
Accepted Libraries

The stage-bot can access the following libraries:

  • axios: Use Axios 0.27.2 and above to make HTTP requests.
  • date-fns: Use date-fns 2.28.0 and above for manipulating Javascript dates.
  • form-data: A library to create readable "multipart/form-data" streams. Can be used to submit forms and file uploads to other web applications.
  • qs: A query string parsing and stringifying library with some added security.
  • querystring: Provides utilities for parsing and formatting URL query strings.
Asynchronicity
  • Asynchronous code is supported, await can be used.
Legacy Versions
  • Code can still be wrapped in backticks (but it is not required): ```. Just remember to use the backslash before a backtick in case they are used within the code: \`
  • Versions prior to 2.0.1 cannot handle asynchronous code.
Attention

All functions have a 30-second timeout limit.

tip
  • See the Embedded Code Editor section for more information on how to use the editor. Running test directly from the code editor is not available.
  • To test your code, you must use the Routine Builder's Run Routine option.

Default Variables

By default, your function can access the followigng variables:

variabledescriptionsyntax
inputAn object that contains the context data. The context data depends on the trigger.Context sturctures depend on the respective Data Model.
outputAn array of objects with all the returned results of previously executed steps in the routine.[{ key: 'step-name', result: Object }]
dataProvides access to data inserted within the Optional Inputs field.Follows JSON format. COTLang can be used within values.
envUsed as URL for network requests within the Cotalker environment.env.EXTERNAL_API_URL, env.EXTERNAL_APP_URL

Return Statements

  • The code must always return an object.
  • The returned object can later be used on the following routine stages and accessed using COTLang script, e.g., $OUTPUT#step-name#data.

Network Requets

  • The JavaScript code runs in a sandboxed node.js environment without access to require, Buffer, or process.env. Therefore, network or IO activity will not work directly. This code block is intended to transform data from the input and output variables, not to store or gather external information.
  • Nonetheless, access to the Axios library is available. With the Axios library, the stage-bot can make network requests. See below for a code sample.
  • An authentication token can be automatically included for Coltalker API requests. See below for details.

Optional Inputs

Use optional inputs to include data not found in the source code, context, or available through a network request. Input types are described below.

To add optional inputs:

ccjs settings panel
  1. Press the Add Optional Inputs button.
  2. The New input field appears. Choose an input type from the list.
  3. Once the input is chosen, press the Add Input button.
note

Repeat the steps to add another input type.

Optional Input Types

Optional Input types are described below:

- Use Default Cotalker Auth

For safety reasons, it is best not to include authentication tokens in your source code. To let Cotalker automatically provide the bot's authentication token to make Cotalker API requests, turn on the option once the Use Default Cotalker Auth input type has been selected.

ccjs settings panel

- Data Object

Add a JSON object to include extra data the source code can fetch. COTLang expressions can also be used as values to contextualize data gathering.

ccjs settings panel

Code Samples

- Payload Sample

data: {
input: {
one: '1',
},
output: [{ a: 'A', b: 'B' }],
code: `
console.log('input', input);
console.log('dateFns', dateFns.format(new Date(), 'yyyy-MM-dd'));
await axios.get('http://webcode.me').then(resp => {
console.log('axios response', resp.data);
});
return event;
`
},

- Data Extraction Sample

This tool is typically used for –but not limited to– automated data extraction from data sources, like collections, and then returning the results in string format for use in the routine's upcoming stage.

Below is a code sample that takes a list-input value of email or name to convert a list of COTUsers into a list of emails or names.

const users = output.find(o => o.key === 'user_step').data;
const type = input.answer.data.find(d => d.identifier === 'survey_identifier').result;

switch (type) {
case 'email': return users.map(u => u.email);
case 'name': return users.map(u => `${u.name.names} ${u.name.lastName || ''}`);
default throw new Error('Unknown type');
}

- cURL Network Request Sample

curl -X "POST" "https://server.com/" \
-H 'Content-Type: application/json; charset=utf-8' \
-d $'{ "code": "return await axios.get(\'http://webcode.me\').then(resp => { return resp.data;});"}'

- Javascript Network Request Sample

This network request obtains the current user's data. The Use Default Cotalker Auth option must be used for this script to work.

const response = await axios({
url: env.EXTERNAL_API_URL + '/api/users/me',
method: 'get'
});

return {
me: response.data
};

- dateFns Sample

This dateFns sample returns the current day of the week and two current time values separated by 5 seconds.

const nameOfDay = dateFns.format(new Date(), "'Today is a' eeee");

// Wait 'n' seconds sync
const waitSeconds = (n) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, n * 1000);
});
};
const start = new Date();
await waitSeconds(5);
const end = new Date();

return {
today: nameOfDay,
wait: {
start,
end
}
};

Inputs

1. Source Code (key: src)

Must return an Object. e.g., return { hello: 'world' };. Variables 'value' and 'output' can be read.
Required: true
Data Type: code javascript

Next Stages

1. SUCCESS

2. ERROR

Outputs

1. error

Error message.
Required: no
Data Type: string

2. data

Returned value.
Required: no
Data Type: any