Publish
Publishes a platform event
Now you know how to generate a command, so let's go directly to the code for this one. In the previous command we saw how to use the Salesforce CLI core libraries to perform an authenticated API request, now let's see how can we perform CRUD operations.
The command we will generate will be like this:
sf events publish NAME --payload '{}'
Let's start by running:
sf dev generate command --name events:publish
And here is the source code for the publish
command:
import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
import { Messages } from '@salesforce/core';
import { AnyJson } from '@salesforce/ts-types';
Messages.importMessagesDirectory(__dirname);
const messages = Messages.load('events-plugin', 'events.publish', [
'summary',
'description',
'examples',
'args.name.summary',
'flags.payload.summary',
'flags.org.summary',
]);
export type EventsPublishResult = {
response: AnyJson;
};
export default class EventsPublish extends SfCommand<EventsPublishResult> {
public static summary = messages.getMessage('summary');
public static description = messages.getMessage('description');
public static examples = messages.getMessages('examples');
// Positional arguments
public static args = [
{
name: 'name',
required: true,
description: messages.getMessage('args.name.summary'),
},
];
// Non-positional arguments
public static flags = {
payload: Flags.string({
summary: messages.getMessage('flags.payload.summary'),
char: 'p',
required: true,
}),
'target-org': Flags.requiredOrg({
summary: messages.getMessage('flags.org.summary'),
char: 'o',
required: true,
}),
};
public async run(): Promise<EventsPublishResult> {
const { args, flags } = await this.parse(EventsPublish);
const name = args.name as string;
// Get the payload and validate it
let payload;
try {
payload = JSON.parse(flags.payload) as AnyJson;
} catch (err) {
this.error("Payload isn't a valid JSON object");
}
// Get the org and the connection
const org = flags['target-org'];
const conn = org.getConnection();
// Create a new platform event by payload
// Note: need to disable some eslint rules because we are using a dynamic payload.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
const response: AnyJson = (await conn.sobject(name).create(payload)) as AnyJson;
this.styledJSON(response);
return {
response,
};
}
}
And the documentation:
# summary
Publishes a platform event
# description
It publishes a platform event by using JSForce and the REST API
# args.name.summary
Event name
# flags.payload.summary
Platform event payload (in JSON format)
# flags.org.summary
Login username or alias for the target org.
# examples
- <%= config.bin %> <%= command.id %> Test_Event__e --payload '{"Name__c": "An event"}'
Last updated