Skip to content

Commit

Permalink
feat: Terminate realtime on logout
Browse files Browse the repository at this point in the history
Attach on one-time handler to unsubscribe realtime
handlers on client logout
  • Loading branch information
ptbrowne committed May 27, 2019
1 parent 1a9a366 commit f9c4110
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
24 changes: 17 additions & 7 deletions src/lib/stack-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -353,13 +353,23 @@ const getSettingsAppURL = function() {
* @returns {Promise}
*/
const init = function({ cozyClient: client, onCreate, onDelete }) {
cozyClient = client
if (!cozyClient.isLogged) return
initializeRealtime({
getApp,
onCreate,
onDelete,
cozyClient
cozyClient = client // Setting global variable
let terminateRealtime
const onLogin = () => {
terminateRealtime = initializeRealtime({
getApp,
onCreate,
onDelete,
cozyClient
})
}
if (cozyClient.isLogged) {
onLogin()
}
cozyClient.once('logout', () => {
if (terminateRealtime) {
terminateRealtime()
}
})
}

Expand Down
18 changes: 17 additions & 1 deletion test/lib/stack-client/stack-client.init.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import CozyClient from 'cozy-client'
import initializeRealtime from 'lib/realtime'

jest.mock('lib/realtime')
initializeRealtime.mockResolvedValue(Promise.resolve())

const { init } = stack

Expand All @@ -30,6 +29,15 @@ describe('stack client', () => {
await init(params)
}

beforeEach(() => {
isLogged = undefined
isPublic = undefined
initializeRealtime.mockReset().mockImplementation(() => {
terminateRealtime = jest.fn()
return terminateRealtime
})
})

afterAll(() => {
jest.restoreAllMocks()
})
Expand All @@ -49,5 +57,13 @@ describe('stack client', () => {
expect(initializeRealtime).toHaveBeenCalled()
expect(initializeRealtime.mock.calls[0][0].cozyClient).toBe(cozyClient)
})

it('should terminate realtime if the user logs out', async () => {
isLogged = true
await setup()
expect(terminateRealtime).not.toHaveBeenCalled()
cozyClient.emit('logout')
expect(terminateRealtime).toHaveBeenCalled()
})
})
})

0 comments on commit f9c4110

Please sign in to comment.