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:
import{exec}from'child_process';import*asfsfrom'fs';exportclassApexExecution{asyncexecute(configApexClassPath: string[]):Promise<string>{constclassListPath=Array.isArray(configApexClassPath)?configApexClassPath:[configApexClassPath];constresults=[];console.log('\nš Executing apex classes...\n');for(constapexClassPathofclassListPath){//check files under recordDefinitionsPath
constclasses=fs.readdirSync(apexClassPath);if(classes.length===0){console.log(`No apex classes found in ${apexClassPath}`);continue;}for(constapexClassofclasses){console.log(`š Executing apex class ${apexClass}`);constcommand=`sfdx force:apex:execute -f ${apexClassPath+apexClass}`;constresult=awaitnewPromise((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);}}returnresults.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.