Skip to content

Commit

Permalink
fix(Realtime): Launch only one connection
Browse files Browse the repository at this point in the history
  • Loading branch information
kosssi committed May 7, 2019
1 parent d5a7573 commit 29fbcb9
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/cozy-realtime/src/Socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ class Socket {
return !!(this._webSocket && this._webSocket.readyState === WebSocket.OPEN)
}

isConnecting() {
return !!(
this._webSocket && this._webSocket.readyState === WebSocket.CONNECTING
)
}

/**
* Establish a realtime connection
*
Expand Down
9 changes: 9 additions & 0 deletions packages/cozy-realtime/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,15 @@ class CozyRealtime {
const { handler, id } = getHandlerAndId(handlerOrId, handlerOrUndefined)
validateParameters(eventName, type, id, handler)

if (this._socket.isConnecting()) {
return new Promise(resolve => {
this._socket.once('open', async () => {
await this.subscribe(eventName, type, handlerOrId, handlerOrUndefined)
resolve()
})
})
}

return new Promise(resolve => {
const key = generateKey(eventName, type, id)
this.on(key, handler)
Expand Down
13 changes: 13 additions & 0 deletions packages/cozy-realtime/src/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,19 @@ describe('CozyRealtime', () => {
cozyStack.emitMessage(type, fakeDoc, 'CREATED')
expect(handler.mock.calls.length).toBe(1)
})

it('should launch only one connection when multiple subscribe is call', async () => {
const handler = jest.fn()
const isOpened = jest.fn()
realtime._socket.on('open', isOpened)
realtime.subscribe('created', type, handler)
realtime.subscribe('created', type, handler)
await pause(10)

expect(isOpened.mock.calls.length).toBe(1)
cozyStack.emitMessage(type, fakeDoc, 'CREATED')
expect(handler.mock.calls.length).toBe(2)
})
})

describe('_haveEventHandler', () => {
Expand Down

0 comments on commit 29fbcb9

Please sign in to comment.