Using Change Data Capture platform events to compute data

Change Data Capture is a feature that, when enabled (under Setup), emits platform events when records in standard or Custom Objects are created, updated, deleted, or undeleted. You do not have to create the platform events because they are defined by the platform. Enabling CDC for your application's objects cannot be packaged, so it is currently something you will need to ask your customers to enable as a post-install task. The setup page looks like this:

The RaceData__ChangeEvent event is defined by the platform and can be subscribed to by implementing an Apex Trigger, much like the example in the previous section. Notice, though, that there is some further specialized handling to determine the nature of the record change through the EventBus.ChangeEventHeader type. Again, it is best that this logic is not conflated with the Domain pattern and is dealt with as a concern within the trigger:

trigger RaceDataChangeEvent on RaceData__ChangeEvent (after insert) {
List<RaceService.ContestantResolvedTelemetry>
resovledTelemetry =
new List<RaceService.ContestantResolvedTelemetry>();
for(RaceData__ChangeEvent event : Trigger.New) {
EventBus.ChangeEventHeader header =
event.ChangeEventHeader;
if (header.changetype == 'CREATE' &&
event.Contestant__c != null) {
RaceService.ContestantResolvedTelemetry telemetry =
new RaceService.ContestantResolvedTelemetry();
telemetry.ContestantId = event.Contestant__c;
telemetry.DriverId = event.DriverId__c;
telemetry.Lap = Integer.valueOf(event.Lap__c);
telemetry.Sector = Integer.valueOf(event.Sector__c);
telemetry.Type = event.Type__c;
telemetry.Value = event.Value__c;
resovledTelemetry.add(telemetry);
}
}
RaceService.processTelemetry(resovledTelemetry);
}

The RaceService.processTelemetry code can be seen by browsing the sample code included in this chapter. Its role is to process race data that has been associated with a contestant and determine whether the sector times received are faster than those previously recorded. If that is the case, it will update the RaceStatistics_c record to allow fans and race team members to see who is currently the fastest per sector.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.121.160