Call Google Apps Script from a Google Cloud Function

51 Views Asked by At

I am attempting to write a Google Cloud Function that will call an Apps Script function that is deployed as an API Executable.

I have confirmed:

  • the Apps Script is deployed as an API Executable and is on the same Google Cloud Project that the Google Cloud Function is
  • the emailToImpersonate has Editor privileges to the Apps Script file
  • the key is a service account that has Domain Wide Delegation for the scopes listed
  • I am obtaining an OAuth 2.0 token using the key and the emailToImpersonate
  • the function I am calling takes no parameters, so I did not include that in the code below

Using the code below, I keep getting an error in my logs stating:

Error: Request contains an invalid argument.

I know that the Apps Script run will not work with a service account, but I thought that by obtaining an OAuth 2.0 token as a specified user, this would be allowed. Was I wrong in assuming this?

I cannot determine why I continue to receive this error, and unfortunately the error logs don't provide additional details.

Google Cloud Function

exports.triggerAppsScripts = onCall({ minInstances: 0, memory: '256 MiB' }, async (request) => {
    log('Starting triggerAppsScripts...');

    const key = await accessSecret('Google_Service_Account_Key').catch(console.error);

    const auth = new google.auth.GoogleAuth({
        credentials: key,
        scopes: [
            'https://www.googleapis.com/auth/admin.directory.user.readonly',
            'https://www.googleapis.com/auth/script.external_request',
            'https://www.googleapis.com/auth/script.projects',
            'https://www.googleapis.com/auth/script.scriptapp',
        ],
        subject: emailToImpersonate,
    });

    const authClient = await auth.getClient();
    google.options({ auth: authClient });
    const scriptService = google.script('v1');

    // Make the API request
    try {
        const res = await scriptService.scripts.run({
            scriptId: scriptId,
            resource: {
                function: functionName,
            },
        });

        log('res', res);

        // Handle the Apps Script function response here
        log(`Apps Script function has finished.`);
    } catch (err) {
        error('The API returned an error: ' + err);
        throw new Error('Error calling Apps Script function.');
    }
});

Apps Script Function

function myFunction() {
  console.log("It worked!")
}
0

There are 0 best solutions below