Created
September 1, 2019 08:16
-
-
Save DJanoskova/fefe93e68757870ed2939152897f0f98 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Ws from '@adonisjs/websocket-client'; | |
| import { getSocketProtocol } from '../utils/data'; | |
| export class SocketConnection { | |
| connect () { | |
| this.ws = Ws(`${getSocketProtocol()}${process.env.REACT_APP_API_URL}`) | |
| // .withApiToken(token) | |
| .connect(); | |
| this.ws.on('open', () => { | |
| console.log('Connection initialized') | |
| }); | |
| this.ws.on('close', () => { | |
| console.log('Connection closed') | |
| }); | |
| return this | |
| } | |
| subscribe (channel, handler) { | |
| if (!this.ws) { | |
| setTimeout(() => this.subscribe(channel), 1000) | |
| } else { | |
| const result = this.ws.subscribe(channel); | |
| result.on('message', message => { | |
| console.log('Incoming', message); | |
| handler(message) | |
| }); | |
| result.on('error', (error) => { | |
| console.error(error) | |
| }); | |
| return result | |
| } | |
| } | |
| } | |
| export default new SocketConnection() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment