Access Multiple DBs in CloudCode Tasks

By default, a DB object is exposed when the CloudCode task is invoked.

Accessing Other Deployments

To access a different deployment within the same app or a different app, a new DB object can be created:

// Same app, different deployment
const otherDB = await CloudCode.createDB('https://{app-deployment-id}.backend.{region-code}.journeyapps.com/', '{backend-deployment-id}', {username: '{backend-deployment-id}', password: 'mypassword'});
const otherDB = await CloudCode.createDB('https://{app-deployment-id}.backend.{region-code}.journeyapps.com/', '{backend-deployment-id}', {token: 'mytoken'});
// Example
const otherDB = await CloudCode.createDB('https://62d541f4156bc4dd685318da.backend.us.journeyapps.com/', '62d541ff9f54b7000706c585', {token: 'mytoken'});


// Different app
const otherDB = await CloudCode.createRemoteDB('https://{app-deployment-id}.backend.{region-code}.journeyapps.com/', '{backend-deployment-id}', {username: '{backend-deployment-id}', password: 'mypassword'});
const otherDB = await CloudCode.createRemoteDB('https://{app-deployment-id}.backend.{region-code}.journeyapps.com/', '{backend-deployment-id}', {token: 'mytoken'});
// Example
const otherDB = await CloudCode.createRemoteDB('https://62d541f4156bc4dd685318da.backend.us.journeyapps.com/', '62d541ff9f54b7000706c585', {token: 'mytoken'});

Accessing other apps with different data models

If you try to use this to access another app's DB, make sure to use createRemoteDB and not createDB. Otherwise, you'll get errors like TypeError: Cannot read property 'where' of undefined

Use environment variables to store credentials

It is best practice to use masked environment variables to store and reference passwords or tokens when using createDB. Read more about environment variables here.

Alternative: Accessing APIv4 directly

APIv4 can be accessed directly using fetch. To avoid hardcoding APIv4 credentials, the details of the current deployment are exposed on the task:

async function downloadUserData(backend) {
 		let response = await fetch(backend.url + '/objects/user.json', {
        headers: {
            Authorization: backend.authorization
        }
    });
    if(!response.ok) {
        throw new Error(response.statusText);
    }
    let data = await response.json();
    return data.objects;
}

async function downloadSchema(backend) {
    let response = await fetch(backend.url + '/datamodel.json', {
        headers: {
            Authorization: backend.authorization
        }
    });
    if(!response.ok) {
        throw new Error(response.statusText);
    }
    return await response.text();
}

export async function run() {
    let users = await downloadUserData(this.backend);
  	console.log('Users', users);

    let schema = await downloadSchema(this.backend);
    console.log('Schema', schema);
}

Last updated