Modular Angular Service for creating Platform Events from AngularJS applications on the Salesforce Platform

In a recent Salesforce project I am working on there was a need for an unified logging and auditing framework that could be used by Lightning Components and AngularJS applications to create auditing records in Salesforce backend.

An additional need well as there was need of a public api that could be consumed by an external system to archive and monitor the records as needed. This is a perfect case for Platform Events. The diagram below describes the high level architecture of the unified auditing service.

For lightning it is very easy to create a reusable component that can be included in all lightning components that need access to this auditing service. This component can use the unified class that creates the platform events using the information provided. The challenge is to use the same apex class in an angularjs application as an angular service. I will be providing a full Auditing Service Framework in a future blog post .. stay tuned. In this blog post I will focus on how we can expose an apex class through the SOAP api in an angular service that can be reused in angular controllers for creating platform events in the backend.

It all starts with a common apex class for creating the platform events. Notice the @AuraEnabled and webservice keywords. This are needed to expose to Lightning and Javascript (AngularJS) respectively.


 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
global with sharing class TestPlatformEventService {

    @AuraEnabled
    webservice static String getServiceName() {
        return TestPlatformEventService.class.getName();
    }

    @AuraEnabled
    webservice static void createPlatformEvent() {
        List<Test_Platform_Event__e> testEvents = new List<Test_Platform_Event__e>();
        testEvents.add(new Test_Platform_Event__e(Description__c = 'Test Event ' + Math.random()));

        // Call method to publish events
        List<Database.SaveResult> results = EventBus.publish(testEvents);

        // Inspect publishing result for each event
        for (Database.SaveResult sr : results) {
            if (sr.isSuccess()) {
                System.debug('Successfully published event.');
            } else {
                for (Database.Error err : sr.getErrors()) {
                    System.debug('Error returned: ' +
                            err.getStatusCode() +
                            ' - ' +
                            err.getMessage());
                }
            }
        }
    }
}

Next is the AngularJS service that can be used in a AngularJS component or directive to invoke an apex webservice method. The reason we are not using the REST API (directly or through a library like jsforce) is due to CORS (Cross-Origin Resource Sharing) support not enabled on the platform. It is only enabled for the Chatter REST API. Please go ahead and vote for the idea to enable CORS support here.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
var serviceModule = angular.module('platformEventServiceModule', []);

serviceModule.service('platformEventService', function() {
    var conn;

    this.init = function(sessionId) {
        sforce.connection.sessionId=sessionId;
    };

 this.getServiceName = function() {
     var result = sforce.apex.execute("TestPlatformEventService", "getServiceName", {});
     console.log(JSON.stringify(result));
 };

 this.createEvent = function() {
     var result = sforce.apex.execute("TestPlatformEventService", "createPlatformEvent", {});
    };
});

Here is a test visualforce page that can be used to test the service.


 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
<apex:page showHeader="false" applyHtmlTag="false" docType="html-5.0">
    <head>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>


        <apex:includeScript value="/soap/ajax/28.0/connection.js" />
        <apex:includeScript value="/soap/ajax/28.0/apex.js" />
        <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.4/angular.min.js"/>
        <apex:includeScript value="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"/>
        <apex:includeScript value="{!$Resource.angularTestPlatformEventService}"/>

        <script>
      var App = angular.module('myApp', ['platformEventServiceModule']);

      App.controller('myctrl', function ($scope, platformEventService) {
         this.$onInit = function() {
                platformEventService.init('{!GETSESSIONID()}');
            }

         $scope.getServiceName = function () {
    $scope.serviceName = platformEventService.getServiceName();
   }

   $scope.createEvent = function () {
       platformEventService.createEvent();
            }
      });
    </script>
    </head>
    <body ng-app="myApp" class="container" ng-controller="myctrl">
    <!--<button  ng-click="getServiceName()">Query</button>-->
    <button  ng-click="createEvent()">Create Event</button>
    <div>{{serviceName}}</div>
    </body>
</apex:page>

For testing the creation of the platform event a simple trigger can be used to create a record everytime
a platform event is created.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
trigger TestPlatformEventTrigger on Test_Platform_Event__e (after insert) {
    List<TestPlatformEventRecord__c> testPlatformEventRecords = new List<TestPlatformEventRecord__c>();
    for(Test_Platform_Event__e evt : Trigger.new) {
        System.debug('Creating record for event: ' + evt);
        TestPlatformEventRecord__c eventRecord = new TestPlatformEventRecord__c();
        eventRecord.User__c = evt.CreatedById;
        eventRecord.Description__c = evt.Description__c;
        testPlatformEventRecords.add(eventRecord);
    }

    insert testPlatformEventRecords;
}

The entire code with the Platform Event (Test_Platform_Event__e) and Custom Object 
(TestPlatformEventRecord__c) can be found on my Github.

Comments

  1. Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. Angel broking customer care

    ReplyDelete
  2. definately enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog! forro festival 2020

    ReplyDelete
  3. digital marketing course in hyderabad by 360DigiTMG is the best one with quality training, best support and more than 9,000 Students Enrolled
    360DigiTMG digital marketing course

    ReplyDelete
  4. If your friend does not answer, you can leave a video message. You can Pay Per Click or the Pay Per Impression. ny web design firms

    ReplyDelete
  5. Exactly how did you discover about this? Effectively i have been looking for this problem for a while. Many thanks individual you might be the brand new main character new york website design company

    ReplyDelete
  6. Despite the fact that you don't store programs on a tablet similarly as you do on a PC, you can in any case run numerous valuable projects on them. 먹튀

    ReplyDelete
  7. Furthermore, with a tad of exploration, you can discover all that you need at no expense. audacity download

    ReplyDelete
  8. A well-written birthday card is original and sincere. It contains a degree of uniqueness and it has the power to get people very emotional and sentimental. love shayari images

    ReplyDelete
  9. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more
    event

    ReplyDelete
  10. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking Best data science courses in hyerabad

    ReplyDelete
  11. Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. שרת וירטואלי

    ReplyDelete
  12. Friend, this web site might be fabolous, i just like it. alkomprar tienda on line

    ReplyDelete
  13. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. pipedrive pricing

    ReplyDelete
  14. I exactly got what you mean, thanks for posting. And, I am too much happy to find this website on the world of Google. sviluppo siti web

    ReplyDelete
  15. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. 1000 Pip Builder Forex Signals Review

    ReplyDelete
  16. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. https//:

    ReplyDelete
  17. hello!! Very interesting discussion glad that I came across such informative post. Keep up the good work friend. Glad to be part of your net community. Atlanta Limousine

    ReplyDelete
  18. This blog has the relevant data according to the topic and precise to the topic.
    Data Science Course in Chennai
    Data Science Course in Bangalore

    ReplyDelete
  19. I was taking a gander at some of your posts on this site and I consider this site is truly informational! Keep setting up.. new company name suggestions

    ReplyDelete
  20. His mom, his significant other and I were never-endingly on tenterhooks, continually in a condition of strain, hanging tight for him to pass on. Events near me

    ReplyDelete
  21. You have shared a lot of information in this content regarding Ventilator Dependent. I would like to express my gratitude to everyone who contributed to this useful article. Keep posting.

    ReplyDelete
  22. ESD Wrist Strap is a basic and widely facility in ESD equipment usage, which is very convenient for workers to operate and enables them to ground while working on the Sensitive Electronics. It is compose of wrist loop and grounding wire, the wrist loop is contact with skin directly. Here's information about anti-static wristband, read on to know.

    ReplyDelete
  23. Wonderful Blog!!! Waiting for your upcoming data... thanks for sharing with us.
    Software Testing Training in Chennai
    Software Testing Online Course

    ReplyDelete
  24. A MEAN stack developer is someone who has knowledge in some particular areas alone. MEAN stack development refers to the development process that falls within these particular set of technologies MongoDB, Expressjs, AngularJs, NodeJS. In simple words, MEAN stack developers are like JS-based application developers. best Udemy courses to learn MEAN stack

    ReplyDelete
  25. A very delightful article that you have shared here. Your blog is a valuable and engaging article for us, and also I will share it with my companions who need this info. promotional products work jobs Thankful to you for sharing an article like this.

    ReplyDelete
  26. Great Post with valuable information. I am glad that I have visited this site. Share more updates.

    Best Online Course For Machine Learning With Python
    Online Learning Machine Learning Python

    ReplyDelete
  27. Thanks a lot for one’s intriguing write-up. It’s actually exceptional. Searching ahead for this sort of revisions.
    data analytics courses in hyderabad with placements

    ReplyDelete
  28. This help takes into account the capacity to arrange the application server. The records important for arrangement are put away outside of the real application server in a bunch of XML design documents. https://www.blackmartappdownloads.com/

    ReplyDelete
  29. I really enjoyed reading your blog. It was very well written and easy to understand. Unlike other blogs that I have read which are actually not very good. Thank you so much!
    Hire Dedicated Angular Developer

    ReplyDelete
  30. Wonderful blog. I am delighted in perusing your articles. This is genuinely an incredible pursuit for me. I have bookmarked it and I am anticipating perusing new articles. Keep doing awesome!
    data analytics training in hyderabad

    ReplyDelete
  31. Thank you for this amazing blog, i am very satisfied with this blog. keep sharing this type of content with us
    apart from this if someone is looking for the best training institute in delhi for any course which is given below,
    you should go to High Technologies Solutions training institute
    this is the one of the best computer institute in delhi for these course .

    Best Training Institute for Python training Course in Delhi, NCR

    Best Training Institute for AutoCAD Training Course in Delhi, NCR

    Best Training Institute for SAP Training Course in Delhi, NCR

    Best Training Institute for SAS Training Course in Delhi, NCR

    Best Training Institute for c++ training Course in Delhi, NCR

    ReplyDelete
  32. Going to the dentist as soon as possible is an important first step when suffering from toothache. Toothache can range from single pain to severe tremors or pain. If you experience this type of discomfort, you should seek immediate medical attention. If you are not sure if you need to see a dentist, you should try using an ice pack or alternative between ibuprofen and acetaminophen. It is important to make a thorough diagnosis so that the best treatment option is effective. If you experience persistent pain after going to the dentist, you should consider an emergency care physician. Read more at urgent care for tooth pain.

    ReplyDelete
  33. You are sharing a particularly decent article here. It is a significant and factual article for us. Thankful to you for sharing an article like this.Blue Collared Recruitment Consultant in UAE

    ReplyDelete
  34. APTRON Solutions is a leading training institute that offers top-notch AngularJS Course in Gurgaon . AngularJS from the best training institute in Gurgaon. Take the first step towards a successful career in web development by enrolling in our AngularJS course at APTRON Solutions. To know more about the course details, batch timings, and fees, visit our website or contact us today. Upgrade your skills with APTRON Solutions and unlock a world of exciting career opportunities in AngularJS development.

    ReplyDelete

Post a Comment