Skip to content

Instantly share code, notes, and snippets.

@OscarScholten
Last active May 12, 2021 02:50
Show Gist options
  • Save OscarScholten/3799223e1c50f6155f0eded939458d70 to your computer and use it in GitHub Desktop.
Save OscarScholten/3799223e1c50f6155f0eded939458d70 to your computer and use it in GitHub Desktop.
SFDX command for setting Apex trigger status to Active or Inactive
import { flags, SfdxCommand } from '@salesforce/command';
import { AnyJson } from '@salesforce/ts-types';
import { Connection, RecordResult } from 'jsforce';
export default class SetTriggerStatus extends SfdxCommand {
public static description = "Set status of all triggers to Active or Inactive";
public static examples = [
`$ sfdx hr2day:setTriggerStatus --targetusername [email protected] -s Active`
];
protected static flagsConfig = {
status: flags.string({ char: 's', description: 'new status for all triggers (Active|Inactive)' })
};
protected static requiresUsername = true;
protected static supportsDevhubUsername = false;
protected static requiresProject = false;
public async run(): Promise<AnyJson> {
if (this.flags.status !== 'Active' && this.flags.status !== 'Inactive') {
this.error(`status parameter must be 'Active' or 'Inactive'`);
}
this.ux.log(`Setting all triggers to status '${this.flags.status}'`);
this.ux.startSpinner('Creating request');
const connection = this.org.getConnection();
const triggers = await this.getTriggerData(connection);
const container = await connection.tooling.sobject('MetadataContainer').create({ 'Name': `container-${new Date().getTime()}` });
await this.populateRequest(connection, triggers, container['id']);
this.ux.stopSpinner();
this.ux.startSpinner('Awaiting response');
const containerAsyncRequest = await connection.tooling.sobject('ContainerAsyncRequest').create({
'MetadataContainerId': container['id'],
'isCheckOnly': false
});
while (true) {
const containerAsyncRequestStatus = await connection.tooling.sobject('ContainerAsyncRequest').retrieve(containerAsyncRequest['id']);
if (containerAsyncRequestStatus['State'] !== 'Queued') {
const deployDetails = containerAsyncRequestStatus['DeployDetails'] !== undefined ? containerAsyncRequestStatus['DeployDetails'] : {};
const failureCount = Array.isArray(deployDetails['componentFailures']) ? deployDetails['componentFailures'].length : 0;
const successCount = Array.isArray(deployDetails['componentSuccesses']) ? deployDetails['componentSuccesses'].length : 0;
if (failureCount > 0 || successCount !== triggers.length) {
this.ux.log(JSON.stringify(containerAsyncRequestStatus, null, 2));
this.error(`Error updating trigger status, see log for details; failureCount=${failureCount} successCount=${successCount} triggerCount=${triggers.length}`);
}
break;
};
}
this.ux.stopSpinner();
const msg = `Successfully updated all ${triggers.length} triggers to status '${this.flags.status}'`;
this.ux.log(msg);
return { 'Result': msg };
}
private populateRequest(connection: Connection, triggers: any[], containerId: string): Promise<void> {
return new Promise((resolve, reject) => {
var promises: Promise<RecordResult>[] = [];
for (var i = 0; i < triggers.length; i++) {
triggers[i]['Metadata']['status'] = this.flags.status;
const apexTriggerMember = {
'MetadataContainerId': containerId,
'ContentEntityId': triggers[i]['Id'],
'Body': triggers[i]['Body'],
'Metadata': triggers[i]['Metadata']
}
promises.push(connection.tooling.sobject('ApexTriggerMember').create(apexTriggerMember));
}
Promise.all(promises)
.then(() => resolve())
.catch(err => reject(err));
});
}
private getTriggerData(connection: Connection): Promise<Array<any>> {
return new Promise((resolve, reject) => {
connection.tooling.sobject('ApexTrigger').find({}, (err, result) => {
if (err) reject(err);
resolve(result);
})
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment