0

I tried to use the cometd streaming api with the push topic /systemTopic/Logging to get in lwc all notification when a log is created. I saw that only the api v36 can be used for that so I use the cometd library(upload with a static ressource ) and this code that I found and change fron internet :

    sessionId = '';
url = '';
@api channel = 'systemTopic/Logging';

//Override the version of api to use cometd. By default it will use 45.
@api apiVersion = '36.0';

//If true then user can see console logs with data.
@api debug = false;

cometd;
subscription;

@track logsArray = [];


async connectedCallback()
{
    let mapping = await initialization();
    mapping = JSON.parse(mapping);
    this.sessionId = mapping.userSessionId;
    this.url = mapping.url;
    console.log(this.sessionId)
    this.loadCometdScript();
}



    /**
     * @author Vishnu Kumar
     * @email [email protected]
     * @desc Loads the cometd static resource.
    */
    loadCometdScript(){
        if( !this.subscription ){
            Promise.all([
                loadScript(this, cometdStaticResource + '/cometd.js')
            ])
            .then(() => {
                this.loadSessionId();
            })
            .catch(error => {
                let message = error.message || error.body.message;
                this.fireErrorEvent(message);
            });
        }
        else{
            this.fireErrorEvent('Subscription already exists.');
            this.consoleLog('(LWC Streaming API) Error: Subscription already exists.');
        }
    }

    /**
     * @author Vishnu Kumar
     * @email [email protected]
     * @desc Loads the session id and create a connection with cometd.
    */
    loadSessionId(){    
            //Initiating Cometd 
            this.cometd = new window.org.cometd.CometD();

            //Configuring Cometd
            this.cometd.configure({
                url: this.url + '/cometd/'+this.apiVersion,
                requestHeaders: { Authorization: 'Bearer ' + this.sessionId,'Content-Type': 'application/json'},
                appendMessageTypeToURL : false
            });
            this.cometd.websocketEnabled = false;

            //Initiating Cometd Handshake
            this.cometd.handshake( (status) => {
                if (status.successful) {
                    this.consoleLog('(LWC Streaming API) Handshake Successful on : '+ this.channel );
                    this.consoleLog('(LWC Streaming API) Handshake Status: '+ JSON.stringify(status) );

                    //Subscribe to channel
                    this.subscription = this.cometd.subscribe( this.channel , (message) => {
                        this.consoleLog('(LWC Streaming API) Message: '+ JSON.stringify(message) );
                        this.fireMessageEvent(message);
                    });
                }
                else{
                    this.consoleLog('(LWC Streaming API) Error in Handshake: '+ JSON.stringify(status) );
                    this.fireErrorEvent(status);
                }
            });

        }

    /**
     * @author Vishnu Kumar
     * @email [email protected]
     * @desc Fire the error event.
    */
    fireErrorEvent(logMsg){
        this.dispatchEvent( 
            new CustomEvent('error', {
                detail: {error: logMsg}
            })
        );
    }

    /**
     * @author Vishnu Kumar
     * @email [email protected]
     * @desc Fire the Payload/Message event.
    */
    fireMessageEvent(payload){
        this.dispatchEvent( 
            new CustomEvent('message', {
                detail: {payload: payload}
            })
        );
    }

    /**
     * @author Vishnu Kumar
     * @email [email protected]
     * @desc Destroy the connection with channel.
    */
    @api
    unsubscribe(){
        //Unsubscribing Cometd
        this.cometd.unsubscribe( this.subscription, {}, (unsubResult) => {
            
            if( unsubResult.successful ) {
                this.consoleLog('(LWC Streaming API) unsubscribed successfully.');

                //Disconnecting Cometd
                this.cometd.disconnect((disResult) => { 
                    if(disResult.successful) {
                        this.consoleLog('(LWC Streaming API) disconnected.');
                    }
                    else{
                        this.consoleLog('(LWC Streaming API) disconnection unsuccessful.');                
                    }
                });
            }
            else{
                this.consoleLog('(LWC Streaming API) unsubscription failed.');
            }
        });
        
        this.subscription = undefined;
    }

    /**
     * @author Vishnu Kumar
     * @email [email protected]
     * @desc Reinitialize the connection with channel.
    */
    @api
    subscribe(){
        this.loadCometdScript();
    }

    /**
     * @author Vishnu Kumar
     * @email [email protected]
     * @desc Return true is connection is not destroyed.
    */
    @api
    checkConnection(){
        if( this.subscription ){
            return true;
        }

        return false;
    }

    /**
     * @author Vishnu Kumar
     * @email [email protected]
     * @desc Print console logs if debug is turned on.
    */
    consoleLog(msg){
        if( this.debug ){
            console.log(msg);
        }
    }

but when I launch it I receive : Access to XMLHttpRequest at 'https://customer-energy-6372-dev-ed.scratch.my.salesforce.com/cometd/36.0?jsonp=_cometd_jsonp_0&message=[{%22id%22:%222%22,%22version%22:%221.0%22,%22minimumVersion%22:%221.0%22,%22channel%22:%22/meta/handshake%22,%22supportedConnectionTypes%22:[%22callback-polling%22],%22advice%22:{%22timeout%22:60000,%22interval%22:0}}]' from origin 'https://customer-energy-6372-dev-ed.scratch.lightning.force.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Someone can help me ?

1 Answer 1

2

Use lightning-emp-api to use the streaming API in LWC. There's no need to use a generic streaming API library in Salesforce.

3
  • sorry but this connector not work with : systemTopic/Logging, this topic need v36 to work so I used the library. Mar 14, 2023 at 4:57
  • @Archer Klien, I used the above api to use platform event on Experience builder site since lightning-emp-api is not supported there. I used the version 48.0 for cometd which is working fine. I am assuming you url is wrong. can you try hardcoding the url and then try first. Mar 14, 2023 at 18:16
  • @AnshulAgrawal no sorry you're right it s working but not with the /systemTopic/Logging... Mar 15, 2023 at 19:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .