Last active
July 4, 2019 01:23
-
-
Save mshanemc/c49ad757f893ecba540b9e46200ae85d to your computer and use it in GitHub Desktop.
wire service for off-core LWC that subscribes to a websocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import wsSubscribe from '../../messages/wsWire/wsWire'; | |
@wire(wsSubscribe, { uri: location.href.replace(/^http/, 'ws'), log: true, fake: true }) | |
wiredResults({ error, data }) { | |
if (error) { | |
console.error('error from ws subscribe wire', error); | |
} else if (data) { | |
console.log(data); | |
this.results = data; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable @lwc/lwc/no-async-operation */ | |
import { register, ValueChangedEvent } from '@lwc/wire-service'; | |
// if you want to set your wire to mock data for building complex ui without connecting to real data | |
import * as fakeData from '../../route/deployMessages/__tests__/data/fullExample.json'; | |
export default function wsSubscribe() { | |
// eslint-disable-next-line no-unused-vars | |
return new Promise((resolve, reject) => { | |
resolve(); | |
}); | |
} | |
register(wsSubscribe, eventTarget => { | |
let config; | |
let pinger; | |
let ws; | |
eventTarget.addEventListener('config', newConfig => { | |
if (newConfig.log) { | |
console.log('new config is', newConfig); | |
} | |
config = newConfig; | |
}); | |
eventTarget.addEventListener('connect', () => { | |
if (config.fake) { | |
eventTarget.dispatchEvent(new ValueChangedEvent({ data: fakeData.default })); | |
} else { | |
if (config.log) { | |
console.log('ws is connecting'); | |
} | |
ws = new WebSocket(config.uri); | |
ws.onopen = () => { | |
if (config.log) { | |
console.log('WS is open!'); | |
} | |
pinger = setInterval(() => { | |
try { | |
ws.send('ping'); | |
} catch (e) { | |
console.log('could not send ws ping', e); | |
} | |
}, 5000); | |
}; | |
ws.onmessage = event => { | |
const newData = JSON.parse(event.data); | |
if (config.log) { | |
console.log('heard ws event', newData); | |
} | |
eventTarget.dispatchEvent(new ValueChangedEvent({ data: newData })); | |
}; | |
ws.onclose = () => { | |
if (config.log) { | |
console.log('WS is closing'); | |
} | |
clearInterval(pinger); | |
}; | |
} | |
}); | |
eventTarget.addEventListener('disconnect', () => { | |
ws.close(); | |
clearInterval(pinger); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment