Is there a way to have a single "shared file" for all cloud code tasks? I'm wanting to put configuration variables in a single spot rather than copying them to every cloud code task or storing in the data model.
Yes there is. There is a special kind of CC task that you can created called a shared
task, documentation here.
Below is an example you can copy with multiple different options of how and where you can specify 'secrets' using the shared task. Note you need to be in OXIDE Advanced mode to do this.
- Create a new CC task with the name 'shared'
- Update the
index.js
to the following:
module.exports = {
// put method and values to share here
secret: 'foo',
add: function add(a, b) {
return a + b;
}
};
- Right click on your newly created 'shared' task in the left hand CloudCode tasks panel and choose to Create CloudCode File - name it 'config.json'
- Update the contents of
config.json
to the following:
{
"secret": "bar",
"not_secret": "foo"
}
- Right click on your newly created 'shared' task in the left hand CloudCode tasks panel and choose to Create CloudCode File - name it 'text.yml'
- Update the contents of
text.yml
to the following:
secret: "bary"
not_secret: "fooy"
- Access the content of your newly created shared task from another CC Task. For example purposes, create a new CC Task called 'test_shared'.
- Update the content of the
index.js
file for the newly createdtest_shared
task to the following:
const fs = require('fs');
const path = require('path');
const sharedTask = require('../shared/index');
const sharedConfig = require('../shared/config.json');
const sharedYaml = fs.readFileSync(path.join(__dirname, '../shared/text.yml'), 'UTF-8');
export async function run() {
console.log('sharedTask: ', sharedTask);
console.log('sharedTask.add(1,2): ', sharedTask.add(1,2));
console.log('sharedConfig: ', sharedConfig);
console.log('sharedYaml: ', sharedYaml);
}
- Test the
test_shared
task, you should get a log that looks like this
10:08:29.866 [TASK:INFO] Start 'EDITOR_TEST' request. Process trace ID: 'P20200501160829AGVrHjvoFH3sU9APRu6hVk'
10:08:29.868 [TASK:DEBUG] ... trimmed
10:08:29.870 [TASK:INFO] sharedTask: { secret: 'foo', add: [Function: add] }
10:08:29.870 [TASK:INFO] sharedTask.add(1,2): 3
10:08:29.870 [TASK:INFO] sharedConfig: { secret: 'bar', not_secret: 'foo' }
10:08:29.870 [TASK:INFO] sharedYaml: secret: "bary"
not_secret: "fooy"
10:08:29.871 [TASK:INFO] Request complete. Response code: 204. Memory used: 51MB.
10:08:30.001 [QUEUE:INFO] Moved from state 'STARTED' to 'COMPLETED'
I hope this helps
this worked great by the way, thank you!