topicMessagesSlice.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
  2. import { TopicMessagesState, ClusterName, TopicName } from 'redux/interfaces';
  3. import { TopicMessage } from 'generated-sources';
  4. import {
  5. getResponse,
  6. showServerError,
  7. showSuccessAlert,
  8. } from 'lib/errorHandling';
  9. import { fetchTopicDetails } from 'redux/reducers/topics/topicsSlice';
  10. import { messagesApiClient } from 'lib/api';
  11. export const clearTopicMessages = createAsyncThunk<
  12. undefined,
  13. { clusterName: ClusterName; topicName: TopicName; partitions?: number[] }
  14. >(
  15. 'topicMessages/clearTopicMessages',
  16. async (
  17. { clusterName, topicName, partitions },
  18. { rejectWithValue, dispatch }
  19. ) => {
  20. try {
  21. await messagesApiClient.deleteTopicMessages({
  22. clusterName,
  23. topicName,
  24. partitions,
  25. });
  26. dispatch(fetchTopicDetails({ clusterName, topicName }));
  27. showSuccessAlert({
  28. id: `message-${topicName}-${clusterName}-${partitions}`,
  29. message: `${topicName} messages have been successfully cleared!`,
  30. });
  31. return undefined;
  32. } catch (err) {
  33. showServerError(err as Response);
  34. return rejectWithValue(await getResponse(err as Response));
  35. }
  36. }
  37. );
  38. export const initialState: TopicMessagesState = {
  39. messages: [],
  40. meta: {
  41. bytesConsumed: 0,
  42. elapsedMs: 0,
  43. messagesConsumed: 0,
  44. isCancelled: false,
  45. },
  46. isFetching: false,
  47. };
  48. const topicMessagesSlice = createSlice({
  49. name: 'topicMessages',
  50. initialState,
  51. reducers: {
  52. addTopicMessage: (state, action) => {
  53. const messages: TopicMessage[] = action.payload.prepend
  54. ? [action.payload.message, ...state.messages]
  55. : [...state.messages, action.payload.message];
  56. return {
  57. ...state,
  58. messages,
  59. };
  60. },
  61. resetTopicMessages: () => initialState,
  62. updateTopicMessagesPhase: (state, action) => {
  63. state.phase = action.payload;
  64. },
  65. updateTopicMessagesMeta: (state, action) => {
  66. state.meta = action.payload;
  67. },
  68. setTopicMessagesFetchingStatus: (state, action) => {
  69. state.isFetching = action.payload;
  70. },
  71. },
  72. extraReducers: (builder) => {
  73. builder.addCase(clearTopicMessages.fulfilled, (state) => {
  74. state.messages = [];
  75. });
  76. },
  77. });
  78. export const {
  79. addTopicMessage,
  80. resetTopicMessages,
  81. updateTopicMessagesPhase,
  82. updateTopicMessagesMeta,
  83. setTopicMessagesFetchingStatus,
  84. } = topicMessagesSlice.actions;
  85. export default topicMessagesSlice.reducer;