Skip to content

Instantly share code, notes, and snippets.

@ruffle1986
Created April 9, 2018 13:50
Show Gist options
  • Save ruffle1986/09f6369fb4ba0520f3455bc0cbf1b0c2 to your computer and use it in GitHub Desktop.
Save ruffle1986/09f6369fb4ba0520f3455bc0cbf1b0c2 to your computer and use it in GitHub Desktop.
real-time messaging with react
import React from 'react';
import PropTypes from 'prop-types';
import { render } from 'react-dom';
const realTimeServiceShape = PropTypes.shape({
subscribe: PropTypes.func.isRequired,
publish: PropTypes.func.isRequired,
getChannel: PropTypes.func.isRequired,
});
class SmartNotes extends React.Component {
static propTypes = {
notes: PropTypes.array,
fetch: PropTypes.func.isRequired, // comming from mapDispatchToProps
realTimeService: realTimeServiceShape.isRequired // comming from the real-time context
}
componentDidMount() {
this.fetch();
this.props.realTimeService.subscribe('notes', () => {
// if I get the appropriate signal from the "notes" channel, let's refetch
// the notes from our db.
this.fetch();
});
}
async fetch() {
this.setState({ loading: true });
this.props.fetch();
this.setState({ loading: false });
}
render() {
return <DumbNotes notes={ this.props.notes } />
}
}
const NotesWithRealTimeContext = () => (
<RealTimeContext.Consumer>
{
(serivce) => (
<SmartNotes realTimeService={ service } />
)
}
</RealTimeContext.Consumer>
)
const RealTimeContext = React.createContext();
interface RealTime {
readonly service: any
getChannel(channel: string): Object
subscribe(channel: string | Object, event: string, callback: Function): void
publish(channel: String | Object, message: string, payload: Object): void
}
class Ably implements RealTime {
service = null
constructor(options: {
apiKey: string
}) {
this.service = new window.Ably.RealTime(options.apiKey);
}
getChannel(channel) {
return this.service.channels.get(channel);
}
subscribe(channel, event, callback) {
if (typeof channel === 'string') {
channel = this.getChannel(channel);
}
channel.subscribe(event, callback);
}
publish(channel, event, payload) {
if (typeof channel === 'string') {
channel = this.getChannel(channel);
}
channel.publish(event, payload);
}
}
class Pusher implements RealTime {
service = null
constructor(options: {
appKey: string,
cluster: string,
encrypted: boolean
}) {
this.service = new window.Pusher(options.appKey, {
cluster: options.cluster,
encrypted: options.encrypted,
});
}
getChannel(channel) {
return this.service.subscribe(channel);
}
subscribe(channel, event, callback) {
if (typeof channel === 'string') {
channel = this.getChannel(channel);
}
channel.bind(event, callback);
}
publish() {
throw new Error(
'It is not recommended to publish Pusher events on the frontend.\n' +
'For this, use the node version on the pusher module and let your backend to handle it.'
);
}
}
const ably = new Ably({
apiKey: 'ablyapikey'
});
// const pusher = new Pusher({
// appKey: 'foobar',
// cluster: 'eu',
// encrypted: true
// });
// const foo = new Whatever();
render((
<RealTimeContext.Provider value={ ably }>
<MyApp />
</RealTimeContext.Provider>
), document.getElementById('root'));
@oroce
Copy link

oroce commented Apr 10, 2018

wouldn't be easier just require the ably module instead of putting another script tag into the app?

@oroce
Copy link

oroce commented Apr 10, 2018

sometimes you used Pusher instead of Ably

@oroce
Copy link

oroce commented Apr 10, 2018

missing await when you do this.props.fetch();, it should be await this.props.fetch();

@ruffle1986
Copy link
Author

wouldn't be easier just require the ably module instead of putting another script tag into the app?

Sure, it's going to be require-ed.

sometimes you used Pusher instead of Ably

Yes, because I gave an example for both of them

missing await when you do this.props.fetch();, it should be await this.props.fetch();

Yes yes, it's just a quick example to demonstrate it. You can take it as a "pseudo code".

@ruffle1986
Copy link
Author

@oroce The point of this gist is to see the concept as a whole. We can talk about the implementation details in the pull request.

Btw, I've been thinking about it and I've ended up not using the context api because it's overengineering. It's enough to have a simple higher order component with which you can get the real-time service we use system-wide. But I still think that keeping the RealTime abstraction is a good idea to easily switch between real-time services.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment