Skip to content

Instantly share code, notes, and snippets.

@jamigibbs
Last active March 31, 2020 02:34
Show Gist options
  • Save jamigibbs/d99d1dbb57508b446d3fd232cb549cee to your computer and use it in GitHub Desktop.
Save jamigibbs/d99d1dbb57508b446d3fd232cb549cee to your computer and use it in GitHub Desktop.
Socket.io import
import { LightningElement, api, wire } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import SOCKET_IO_JS from '@salesforce/resourceUrl/socketiojs';
import USER_ID from '@salesforce/user/Id';
// Your Heroku server link as a custom label and looks something like this:
// wss://my-heroku-app.herokuapp.com/
import WEBSOCKET_SERVER_URL from '@salesforce/label/c.websocket_server_url';
import getTodayMessages from '@salesforce/apex/ChatController.getTodayMessages';
import getActiveChatUsers from '@salesforce/apex/ChatController.getActiveChatUsers';
import setUserChatActive from '@salesforce/apex/ChatController.setUserChatActive';
import setUserChatInactive from '@salesforce/apex/ChatController.setUserChatInactive';
export default class WebsocketChat extends LightningElement {
@api userId = USER_ID;
@api timeString;
@api message;
@api error;
@api isChatActive = false;
@api isTyping = false;
_socketIoInitialized = false;
_socket;
@wire(getRecord, {recordId: USER_ID, fields: [CHAT_ACTIVE_FIELD]})
wiredUser({error, data}) {
if (error) {
this.error = error;
} else if (data) {
this.isChatActive = data.fields.Chat_Active__c.value;
}
}
@wire(getTodayMessages)
wiredMessages
@wire(getActiveChatUsers)
wiredChatUsers
/**
* Loading the socket.io script.
*/
renderedCallback(){
if (this._socketIoInitialized) {
return;
}
this._socketIoInitialized = true;
Promise.all([
loadScript(this, SOCKET_IO_JS),
])
.then(() => {
this.initSocketIo();
})
.catch(error => {
// eslint-disable-next-line no-console
console.error('loadScript error', error);
this.error = 'Error loading socket.io';
});
}
initSocketIo(){
// eslint-disable-next-line no-undef
this._socket = io.connect(WEBSOCKET_SERVER_URL);
// ADDITIONAL SOCKET EVENT HANDLING WILL GO HERE
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment