Running Apex CLS File on CLI

In this article, we will explore how to run an Apex CLS file on the Command Line Interface (CLI) using a TypeScript code snippet. This code snippet will allow you to execute Apex classes in a specified folder, and return the results to the CLI.

Create a new TypeScript file named apexExecution.ts in your preferred code editor. Copy and paste the following code snippet into the file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { exec } from 'child_process';
import * as fs from 'fs';

export class ApexExecution {
  async execute(configApexClassPath: string[]): Promise<string> {
    const classListPath = Array.isArray(configApexClassPath)
      ? configApexClassPath
      : [configApexClassPath];
    const results = [];
    console.log('\nšŸ“ž Executing apex classes...\n');
    for (const apexClassPath of classListPath) {
      //check files under recordDefinitionsPath
      const classes = fs.readdirSync(apexClassPath);
      if (classes.length === 0) {
        console.log(`No apex classes found in ${apexClassPath}`);
        continue;
      }
      for (const apexClass of classes) {
        console.log(`šŸ“ž Executing apex class ${apexClass}`);
        const command = `sfdx force:apex:execute -f ${apexClassPath + apexClass}`;
        const result = await new Promise((resolve, reject) => {
          exec(command, (err, stdout, stderr) => {
            if (err) {
              console.log(
                `āŒ Error occurred while executing Apex class... ${apexClass}: ${stderr}\n`
              );
              reject(err);
            } else {
              console.log(`āœ… Apex execution successful\n`);
              resolve(stdout);
            }
          });
        });
        results.push(result);
      }
    }
    return results.join('\n');
  }
}

Understanding the Code

The code snippet above defines a TypeScript class named ApexExecution. This class has a single method named execute, which accepts an array of strings as its parameter. This array represents the paths to the Apex classes that you want to execute.

The execute method uses the fs module to read the contents of each folder specified in the configApexClassPath parameter. It then loops through each Apex class in the folder and executes it using the Salesforce CLI’s force:apex:execute command.

If the execution of the Apex class is successful, the method will log a success message to the CLI and return the output generated by the command. If an error occurs, the method will log an error message to the CLI and reject the Promise.

Cheers! šŸŗ