Repository navigation
feat(ScheduleMessages): load scheduled messaged in Chat and add hooks #3353
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
NikolaGoranNaumovski
wants to merge
1
commit into
release-v14
Choose a base branch
from
feat/react-1386-scheduled-messages-wiring
base: release-v14
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
226 changes: 226 additions & 0 deletions
226
src/components/Chat/__tests__/ChatScheduledMessages.test.tsx
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,226 @@ | ||
| import React, { StrictMode } from 'react'; | ||
| import { act, cleanup, render } from '@testing-library/react'; | ||
| import { ErrorFromResponse } from 'stream-chat'; | ||
| import type { APIErrorResponse, StreamChat } from 'stream-chat'; | ||
|
|
||
| import { Chat } from '..'; | ||
| import { | ||
| dispatchConnectionChangedEvent, | ||
| dispatchConnectionRecoveredEvent, | ||
| dispatchScheduledMessageEvent, | ||
| generateScheduledMessage, | ||
| getTestClient, | ||
| getTestClientWithUser, | ||
| } from '../../../mock-builders'; | ||
|
|
||
| const renderChat = async (client: StreamChat, { strict = false } = {}) => { | ||
| const chat = <Chat client={client}>{null}</Chat>; | ||
|
|
||
| let result!: ReturnType<typeof render>; | ||
| await act(() => { | ||
| result = render(strict ? <StrictMode>{chat}</StrictMode> : chat); | ||
| }); | ||
| return result; | ||
| }; | ||
|
|
||
| const countListeners = (client: StreamChat, type: string) => | ||
| client.listeners[type]?.length ?? 0; | ||
|
|
||
| const featureDisabledError = () => | ||
| new ErrorFromResponse<APIErrorResponse>('failed', { | ||
| code: 114, | ||
| response: { | ||
| data: { | ||
| code: 114, | ||
| duration: '', | ||
| exception_fields: { reason: 'scheduled_messages_disabled' }, | ||
| message: 'failed', | ||
| more_info: '', | ||
| StatusCode: 400, | ||
| }, | ||
| } as ErrorFromResponse<APIErrorResponse>['response'], | ||
| status: 400, | ||
| }); | ||
|
|
||
| describe('Chat scheduled messages wiring', () => { | ||
| afterEach(cleanup); | ||
|
|
||
| it('loads the scheduled messages once the user is connected', async () => { | ||
| const client = await getTestClientWithUser({ id: 'user-1' }); | ||
|
|
||
| await renderChat(client); | ||
|
|
||
| expect(client.queryScheduledMessages).toHaveBeenCalledTimes(1); | ||
| expect(client.queryScheduledMessages).toHaveBeenCalledWith({ limit: 100 }); | ||
| expect(client.scheduledMessages.state.getLatestValue().isLoaded).toBe(true); | ||
| }); | ||
|
|
||
| it('does not load before a user is connected', async () => { | ||
| const client = getTestClient(); | ||
|
|
||
| await renderChat(client); | ||
|
|
||
| expect(client.queryScheduledMessages).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('loads when a user connects after the first render, without a re-render', async () => { | ||
| const client = getTestClient(); | ||
| await renderChat(client); | ||
|
|
||
| await client.connectUser({ id: 'user-1' }, 'token'); | ||
| await act(() => { | ||
| dispatchConnectionChangedEvent(client, true); | ||
| }); | ||
|
|
||
| expect(client.queryScheduledMessages).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('does not load when the connection goes offline', async () => { | ||
| const client = getTestClient(); | ||
| await renderChat(client); | ||
|
|
||
| await client.connectUser({ id: 'user-1' }, 'token'); | ||
| await act(() => { | ||
| dispatchConnectionChangedEvent(client, false); | ||
| }); | ||
|
|
||
| expect(client.queryScheduledMessages).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('does not load for an anonymous user', async () => { | ||
| const client = await getTestClientWithUser({ id: '!anon' }); | ||
| client.anonymous = true; | ||
|
|
||
| await renderChat(client); | ||
|
|
||
| expect(client.queryScheduledMessages).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('retries a failed load when the connection comes back', async () => { | ||
| const client = await getTestClientWithUser({ id: 'user-1' }); | ||
| vi.mocked(client.queryScheduledMessages).mockRejectedValueOnce(new Error('offline')); | ||
| await renderChat(client); | ||
|
|
||
| await act(() => { | ||
| dispatchConnectionChangedEvent(client, true); | ||
| }); | ||
|
|
||
| expect(client.queryScheduledMessages).toHaveBeenCalledTimes(2); | ||
| expect(client.scheduledMessages.state.getLatestValue().isLoaded).toBe(true); | ||
| }); | ||
|
|
||
| it('retries a failed load on connection.recovered', async () => { | ||
| const client = await getTestClientWithUser({ id: 'user-1' }); | ||
| vi.mocked(client.queryScheduledMessages).mockRejectedValueOnce(new Error('offline')); | ||
| await renderChat(client); | ||
|
|
||
| await act(() => { | ||
| dispatchConnectionRecoveredEvent(client); | ||
| }); | ||
|
|
||
| expect(client.scheduledMessages.state.getLatestValue().isLoaded).toBe(true); | ||
| }); | ||
|
|
||
| it('does not retry or warn when the feature is disabled', async () => { | ||
| const client = await getTestClientWithUser({ id: 'user-1' }); | ||
| vi.mocked(client.queryScheduledMessages).mockRejectedValueOnce( | ||
| featureDisabledError(), | ||
| ); | ||
| const loggerSpy = vi.spyOn(client, 'logger'); | ||
| await renderChat(client); | ||
|
|
||
| await act(() => { | ||
| dispatchConnectionChangedEvent(client, true); | ||
| }); | ||
|
|
||
| expect(client.queryScheduledMessages).toHaveBeenCalledTimes(1); | ||
| expect(client.scheduledMessages.state.getLatestValue().isDisabled).toBe(true); | ||
| expect(loggerSpy).not.toHaveBeenCalledWith( | ||
| 'warn', | ||
| 'scheduledMessages: load failed', | ||
| expect.anything(), | ||
| ); | ||
| }); | ||
|
|
||
| it('does not load again when the connection comes back after a successful load', async () => { | ||
| const client = await getTestClientWithUser({ id: 'user-1' }); | ||
| await renderChat(client); | ||
|
|
||
| await act(() => { | ||
| dispatchConnectionChangedEvent(client, true); | ||
| }); | ||
|
|
||
| expect(client.queryScheduledMessages).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('does not load again on re-render', async () => { | ||
| const client = await getTestClientWithUser({ id: 'user-1' }); | ||
| const { rerender } = await renderChat(client); | ||
|
|
||
| await act(() => { | ||
| rerender(<Chat client={client}>{null}</Chat>); | ||
| }); | ||
|
|
||
| expect(client.queryScheduledMessages).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('queries and subscribes once under StrictMode', async () => { | ||
| const client = await getTestClientWithUser({ id: 'user-1' }); | ||
|
|
||
| await renderChat(client, { strict: true }); | ||
|
|
||
| expect(client.queryScheduledMessages).toHaveBeenCalledTimes(1); | ||
| expect(countListeners(client, 'scheduled_message.created')).toBe(1); | ||
| expect(countListeners(client, 'scheduled_message.sent')).toBe(1); | ||
| }); | ||
|
|
||
| it('keeps the store in sync from events while mounted', async () => { | ||
| const client = await getTestClientWithUser({ id: 'user-1' }); | ||
| const scheduledMessage = generateScheduledMessage(); | ||
| await renderChat(client); | ||
|
|
||
| act(() => { | ||
| dispatchScheduledMessageEvent({ | ||
| client, | ||
| scheduledMessage, | ||
| type: 'scheduled_message.created', | ||
| }); | ||
| }); | ||
|
|
||
| expect(client.scheduledMessages.getFromState(scheduledMessage.id)).toEqual( | ||
| scheduledMessage, | ||
| ); | ||
| }); | ||
|
|
||
| it('unsubscribes on unmount', async () => { | ||
| const client = await getTestClientWithUser({ id: 'user-1' }); | ||
| const connectionChangedListeners = countListeners(client, 'connection.changed'); | ||
| const connectionRecoveredListeners = countListeners(client, 'connection.recovered'); | ||
| const { unmount } = await renderChat(client); | ||
|
|
||
| unmount(); | ||
|
|
||
| expect(client.scheduledMessages.hasSubscriptions).toBe(false); | ||
| expect(countListeners(client, 'scheduled_message.created')).toBe(0); | ||
| expect(countListeners(client, 'connection.changed')).toBe(connectionChangedListeners); | ||
| expect(countListeners(client, 'connection.recovered')).toBe( | ||
| connectionRecoveredListeners, | ||
| ); | ||
| }); | ||
|
|
||
| it('logs and keeps rendering when the load fails', async () => { | ||
| const client = await getTestClientWithUser({ id: 'user-1' }); | ||
| const error = new Error('boom'); | ||
| vi.mocked(client.queryScheduledMessages).mockRejectedValueOnce(error); | ||
| const loggerSpy = vi.spyOn(client, 'logger'); | ||
|
|
||
| await renderChat(client); | ||
|
|
||
| expect(loggerSpy).toHaveBeenCalledWith( | ||
| 'warn', | ||
| 'scheduledMessages: load failed', | ||
| expect.objectContaining({ error }), | ||
| ); | ||
| expect(client.scheduledMessages.state.getLatestValue().lastQueryError).toBe(error); | ||
| }); | ||
| }); |
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import { useEffect } from 'react'; | ||
| import { getScheduledMessageErrorReason, ScheduledMessageErrorReason } from 'stream-chat'; | ||
| import type { Event, StreamChat } from 'stream-chat'; | ||
|
|
||
| const isFeatureDisabledError = (error: Error) => | ||
| getScheduledMessageErrorReason(error) === ScheduledMessageErrorReason.Disabled; | ||
|
|
||
| export const useLoadScheduledMessages = (client: StreamChat) => { | ||
| useEffect(() => { | ||
| const { scheduledMessages } = client; | ||
|
|
||
| const loadScheduledMessages = () => { | ||
| const { isDisabled, isLoaded, isLoading } = | ||
| scheduledMessages.state.getLatestValue(); | ||
| const hasConnectedUser = !!client.user?.id && !client.anonymous; | ||
|
|
||
| const shouldLoad = hasConnectedUser && !isDisabled && !isLoaded && !isLoading; | ||
|
|
||
| if (!shouldLoad) return; | ||
|
|
||
| scheduledMessages.load().catch((error: Error) => { | ||
| if (isFeatureDisabledError(error)) return; | ||
|
|
||
| client.logger('warn', 'scheduledMessages: load failed', { | ||
| error, | ||
| tags: ['scheduled_messages'], | ||
| }); | ||
| }); | ||
| }; | ||
|
|
||
| const loadWhenOnline = ({ online }: Event) => { | ||
| if (online) loadScheduledMessages(); | ||
| }; | ||
|
|
||
| loadScheduledMessages(); | ||
|
|
||
| const subscriptions = [ | ||
| client.on('connection.changed', loadWhenOnline), | ||
| client.on('connection.recovered', loadScheduledMessages), | ||
| ]; | ||
|
|
||
| return () => subscriptions.forEach(({ unsubscribe }) => unsubscribe()); | ||
| }, [client]); | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: GetStream/stream-chat-react
Length of output: 3081
Script executed:
Repository: GetStream/stream-chat-react
Length of output: 4218
Script executed:
Repository: GetStream/stream-chat-react
Length of output: 6083
Web query:
"stream-chat" "9.54.0" ScheduledMessageManager ScheduledMessageErrorReasonResult:
Script executed:
Repository: GetStream/stream-chat-react
Length of output: 3242
Bump
stream-chatbefore merging.package.jsonandyarn.lockstill resolvestream-chatto9.54.0. That release does not publicly export the scheduled-message manager orgetScheduledMessageErrorReasonused by the changed files. Thetypesscript and the TypeScript phase ofbuildtherefore fail with missing exports. Updatepackage.jsonto the released SDK version containing these symbols and regenerateyarn.lock.GitHub Actions: Size / 0_Compressed Size.txt
[error] 2-10: TypeScript compilation failed: 'stream-chat' does not export getScheduledMessageErrorReason or ScheduledMessageErrorReason (TS2305); StreamChat also has no 'scheduledMessages' property (TS2339). Failed step: tsc --project tsconfig.lib.json.
GitHub Actions: Size / Compressed Size
[error] 2-10: TypeScript (tsc --project tsconfig.lib.json): TS2305: stream-chat does not export 'getScheduledMessageErrorReason' or 'ScheduledMessageErrorReason'; TS2339: Property 'scheduledMessages' does not exist on type 'StreamChat'.